Russell Jones Russell Jones - 1 month ago 13
Javascript Question

Detecting shape coordinates in Canvas

I'm writing drag & drop functionality in my HTML5 Canvas application and am wondering how to detect if I'm clicking on a shape other than a rectangle or square, in which case I would do something like this inside of my 'mousedown' event handler:

if (evt._x > 13 && evt._x < 202 .... ) {}

I don't see how to easily do something like that with an arc like this:

ctx.arc(25, 25, 20, 0, (Math.PI/180)*360);

I hope that is clear, thank you in advance.

Answer

Just use isPointInPath, which checks if a given point is within the current drawing path. If you're drawing multiple shapes to the canvas, than a good technique is to associate each of your shapes with a "hidden" canvas, draw each path to its respective canvas, than test isPointInPath against each of these, offsetting the destination/mouse coordinates as needed. Theres no reason to resort to your own calculations for this.