Skip to content

Instantly share code, notes, and snippets.

@fallenartist
Created February 24, 2016 16:20
Show Gist options
  • Save fallenartist/538244d124448365a6fd to your computer and use it in GitHub Desktop.
Save fallenartist/538244d124448365a6fd to your computer and use it in GitHub Desktop.
JavaScript function checking if a point falls inside a polygon.
// +Jonas Raoni Soares Silva
// @http://jsfromhell.com/math/is-point-in-poly [rev. #0]
// usage:
// points = [ {x: X1, y: Y1}, {x: X2, y: Y2}, ... , {x: Xn, y: Yn} ];
// alert( isPointInPoly(points, {x: mouseX, y: mouseY}) ? "In" : "Out" );
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment