Coffeehouse Thread

6 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

Getting images created in a Canvas context to respond to an event

Back to Forum: Coffeehouse
  • User profile image
    123logd

    Hello, I am creating a rudimentary game for educational purposes.  I simply want to show at random intervals of time (up to 3 seconds) 1 to all images in a 5 image array.  The images will display at random locations within the canvas.  The images will disappear in random intervals of time (up to 3 seconds).  If the user clicks on an image before it disappears a running score is displayed and the image lights up with a yellow border.  I am using CSS for class types to light up if the image is clicked.  I can addEventListeners to the various images created and I set the className as appropriate.  I use ctx = canvas.getContext("2d") and ctx.drawImage to show the image.  The image is never getting the event.  Any code snippet to help me out?  Maybe I am barking up the wrong tree using Canvas?  I am hoping the experts in the coffee house can show me the code snip for this very simple example.  codeShow samples do not quite have the pieces for this.  Thanks

  • User profile image
    Harlequin

    Did you try to do a detailed post with code on StackOverflow? There's probably devs there that watch posts with tags with HTML5 and Canvas. Then you're reaching a thousand devs instead of two here that might know Smiley

  • User profile image
    cbae

    Why use a canvas? Why not use an img element and move it around with JavaScript? If these are images that you need to draw dynamically, you need to add the event handler to the canvas element, and then figure if the click coordinates are within the bounds of any of the images you drew.

  • User profile image
    ZippyV

    , cbae wrote

    Why use a canvas? Why not use an img element and move it around with JavaScript?

    Indeed, when you put something on a canvas it becomes part of the canvas. No more css or onclick events. Just use a div as container with "position: relative;" and put img element in there with "position: absolute;"

  • User profile image
    123logd

    Thank you.  I will proceed without Canvas.  So, what applications are ideal for Canvas?

  • User profile image
    cbae

    If you create a game that uses a game loop, then you're not going to responding to events on individual elements on the screen. You would simply calculate movements of the player/enemies, determine collisions, and then refresh the screen by redrawing everything. That's when you would use a canvas.

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.