Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a shape was clicked (HTML5 canvas)?

I am drawing different shapes like rectangle, triangle, hexagon etc. using the canvas and lineTo method like in this blog. I just want a simple way to find if I clicked inside a shape. I can do it by filling the shape with some color and the checking if the point I clicked has this color but I don't want to use fill color method. Is there any other way to do it?

Also found isPointInPath but it did not work.

like image 876
Sandeep Kumar Avatar asked Feb 12 '13 11:02

Sandeep Kumar


People also ask

How do I know if my canvas is clicked?

To detect the click, the canvas element is first selected using the querySelector() method. The addEventListener() method is used on this element to listen the 'mousedown' event. This event is triggered whenever a mouse button is pressed down.

What does canvas tag indicate?

The <canvas> tag is used to draw graphics, on the fly, via scripting (usually JavaScript). The <canvas> tag is transparent, and is only a container for graphics, you must use a script to actually draw the graphics.

How does canvas coordinates work?

Canvas Coordinates The canvas is a two-dimensional grid. The coordinate (0, 0) is at the upper-left corner of the canvas. Along the X-axis, values increase towards the right edge of the canvas. Along the Y-axis, values increase towards the bottom edge of the canvas.


2 Answers

Check in here:

Javascript check Mouse clicked inside the Circle or Polygon

meouw answer works for sure I've test it and guarantee it works. It seems that there are some other solutions, too that have been upvoted, maybe you can try them, either

like image 128
kidwon Avatar answered Oct 11 '22 14:10

kidwon


You could either try some canvas frameworks like http://kineticjs.com/ (check events section) which support already clickable elements out of the box or you'll need to write two functions, one which gives you your relative mouse click coordinates inside the canvas element (I used the one described here: https://stackoverflow.com/a/5932203/532102) and after write another function which checks if the returned mouse coordinates intersect with your shape on the canvas.

like image 21
tmaximini Avatar answered Oct 11 '22 14:10

tmaximini