views:

53

answers:

4

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.

+2  A: 

First you check if the click is within a shape's bounding box (the smallest rectangle which fully encloses the shape). If it is, then you do the more complex math to determine if the click is within the shape itself. You'll have to implement this math yourself as I don't think there's anything built-in for it.

bemace
I see, that makes sense! Looks like I have some playing around to do. Thanks again.
roosta
+1  A: 

You'll get the formula you need here and also in Polygon article of Wikipedia.

Vantomex
A: 

This may sound stupid, but you can use <area> tags inside a <map> over an <img> to create interactive polygonal shapes. They have their own onclicks/mouseovers/etc. already implemented by all browsers.

atomizer
+2  A: 

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.

Angiosperm
That's quite brilliant. I've never heard of isPointInPath obviously, thanks, I'm going to give it a try!
roosta