Created
February 24, 2016 16:20
-
-
Save fallenartist/538244d124448365a6fd to your computer and use it in GitHub Desktop.
JavaScript function checking if a point falls inside a polygon.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// +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