2

I've draw an image inside a canvas tag. How could I add events to it? I want to do something when user clicks in that image.

character.addEventListener('click', function() { alert('foo'); }, true);
/* character is a var (image object) within a canvas */

Thank you.

thomas
  • 21
  • 1
  • 3
  • 1
    If you use canvas library like Fabric.js, it would take care of underlying shape click detection. E.g.: `canvas.add(myImg); myImg.on('click', function(){ console.log('image was clicked') })` – kangax Jul 24 '12 at 09:41

3 Answers3

2

get click event of each rectangle inside canvas?

Further more, I have found that this answer does not work in Mozilla.

Instead use clientX instead of offsetX.

Example, I have created a dynamic canvas image gallery on github at: https://github.com/michaelBenin/fi-test

Every time the window is resized I recalculate the x, y, of each image drawn, from there I run the collisions function when the canvas is clicked.

Basically you get the x, y value from the click event and check to see if there is anything on the canvas at those coordinates.

Here is another good link on registering click events inside of canvas: http://eli.thegreenplace.net/2010/02/13/finding-out-the-mouse-click-position-on-a-canvas-with-javascript/

Community
  • 1
  • 1
Michael Benin
  • 4,317
  • 2
  • 23
  • 15
2

There's no way to add event handlers to actual drawings on the canvas. You can handle events for the entire canvas - that's it.

Your options at this point is to either add an abstraction over the canvas, and lookup drawings you have there based on coordinates from canvas click events - or to drop canvas altogether and go for e.g. svg. The Raphaël library (http://raphaeljs.com/) can help you with the latter.

einaros
  • 641
  • 3
  • 8
0

See blow link,there is a sample

http://www.html5canvastutorials.com/cookbook/ch6/1369_06_03/

See the source of page

ali bagheri
  • 139
  • 2
  • 5