# javascript - Check a point location in a particular area on html canvas

I want check whether a point(x,y) is in a particular area on a canvas. For example if I have an area of 100X100 on an html canvas, then i want to find that whether a point (x, y) lies inside this area or it is outside the area.

This detection is to be done using javascript and jquery.

Thanx.

depends on what use case you need it for:

1. MouseOver/Click: as long as your canvas is the only thing with moving elements and you DO NOT need support for safari / iOS an good ol' fashioned image map actually does the job. (a 1px*1px transparent gif stretched over the dimensions of the canvas using the image map)
2. Any Point (including mouse): use a formula to calculate if the point is inside or outside the polygon. the following script (while not from me) solves this:

``````//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/math/is-point-in-poly [rev. #0]

function isPointInPoly(poly, pt){
for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i)
((poly[i].y <= pt.y && pt.y < poly[j].y) || (poly[j].y <= pt.y && pt.y < poly[i].y))
&& (pt.x < (poly[j].x - poly[i].x) * (pt.y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x)
&& (c = !c);
return c;
}
``````

on his page, Jonas also gives an example of how to use it. basically poly is an array of objects containing the points of the polygon and pt is an object with the point you want to test:

``````var polygon = [
{x: 0, y: 0},
{x: 0, y: length},
{x: length, y: 10},
{x: -length, y: -10},
{x: 0, y: -length},
{x: 0, y: 0}
];

var testpoint= {x: 1, y:2};
if(isPointInPoly(polygon,testpoint)) { /* do something */ }
``````

if it's for mouseposition you should bind the whole thing to mousemove which again can be en-/disabled upon mouseenter/mouseleave - all events of the canvas node

3. any point: use the canvas function isPointInPath() as explained here: http://canvas.quaese.de/index.php?nav=6,42&doc_id=31 Though AFAIK this only works if you have only one path on the canvas (you could use multiple canvas's) - or repaint each polygon and test it while doing so.

I personally prefer option 2. if you need further help on getting the mouse coordinates a google search should give you the right pages here on stackoverflow (or see the "related" section to the right)