Search code examples
javascriptcanvasclickcollision-detectionshapes

Click on given element in canvas


Is there any trick to determine if user clicks on given element rendered in canvas? For example I'm displaying rhombus from .png file with transparent background and i want to know if user click inside or outside that figure (like mouse-element collision).


Solution

  • There is no concept of individual elements in a canvas - it is simply just an area that you're drawing pixels onto. SVG on the other hand is made up of elements which you can then bind events to. However there are a few approaches you can take to add click events to canvas:

    1. Position an html element that overlays the area on the canvas you want to be clickable. A for a rectangular area or an image map for something more irregular.

    2. Use separate canvases for each element that you want to be clickable.

    3. CAKE - I haven't used this myself, but it's description is "SVG sans the XML". This may cover your needs. Demos here http://glimr.rubyforge.org/cake/canvas.html#EditableCurve