Russell
Russell

Reputation: 978

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.

Upvotes: 1

Views: 4464

Answers (4)

Angiosperm
Angiosperm

Reputation: 454

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.

Upvotes: 9

atomizer
atomizer

Reputation: 4646

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.

Upvotes: 0

Vantomex
Vantomex

Reputation: 2295

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

Upvotes: 1

Brad Mace
Brad Mace

Reputation: 27886

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.

Upvotes: 2

Related Questions