user1055096
user1055096

Reputation: 11

Create an event on a dynamically placed image on an HTML5 canvas

I'm placing a tile dynamically from javascript, so for each tile I need an onclick event.

What I'm doing is :

var image = new Image();
image.src = "tile.png";
for(var i=0;i<20;i++){
   for(var j=0;j<20;j++){
      ctx.drawImage(image,i,j,20,20,i,j,20,20);
   }
}

however I can't place an event on image variable, that won't work. Is there a possible way to pass an event handler to drawImage?

I just wish for the tile number on click of the canvas, Please suggest any other alternative for the same. Thanks.

Upvotes: 1

Views: 2743

Answers (2)

Rob
Rob

Reputation: 1216

If you use JQuery (1.7.1) you can add a click event for each image using live which adds the click event to the dom on the fly. So change your code as follows. Comments are in the method. Let me know if this works for you.

Rob

Not sure if you have some code to grab the tile from the image but you might be able to use this...

Tileset for HTML5 canvas game

var iCount = 1
for(var i=0;i<20;i++){
   for(var j=0;j<20;j++){
      iCount = iCount +1

      //create image in the loop
      var image = new Image();
      image.src = "tile.png";
      image.attr('class', 'theimage_' + iCount );

      //in the loop each image has a unique class name which you 
      //can attach to the dom via jquery live
      ctx.drawImage(image,i,j,20,20,i,j,20,20);

      //you can either attach some logic here or outside of the loop
      $('.theimage_' + iCount ).live('click', function() {
        alert("You Clicked: " + '.theimage_' + iCount );
      });

   }
}

Upvotes: -1

steveyang
steveyang

Reputation: 9298

Why it doesn't work

you can't bind an event on a javaScript object, you must bind it with a domElement.

The Solution

You need to append the image to one domElement and bind the click event there. Add these lines to your current code:

$(".image_container").append(image).click(function () {
  //what you want to do when the canvas is clicked.
});

Upvotes: 3

Related Questions