Targeting And Identifying Shapes In The Canvas
Solution 1:
which will simply give me the x and y coordinates of the mouse click, and then I'd run a custom function to seek out the shape that is sitting at the clicked coordinates
That's exactly what you need to do. More accurately, you'd probably iterate over the shapes and check whether the clicked point was inside any of them.
Is there any native function that enable me to identify an element on the canvas?
No. And be careful with your terminology: these aren't elements like you'd find in the DOM.
Problem is, this isn't always bulletproof – in the case of triangles for example, a mouse click within it's boundary won't always return the triangle.
You need to check whether the point is inside each triangle, not its bounding box. Do a google search for "point triangle collision detection" or "point triangle intersection" for a bunch of results. This is more of a math question than it is a programming question.
You could use the collide2D library, but honestly you should probably just do the detection yourself for something as simple as this.
Post a Comment for "Targeting And Identifying Shapes In The Canvas"