出处: https://github.com/substack/point-in-polygon/blob/master/index.js
github: https://github.com/substack/point-in-polygon
module.exports = function (point, vs) {
// ray-casting algorithm based on
// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html var x = point[0], y = point[1]; var inside = false;
for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
var xi = vs[i][0], yi = vs[i][1];
var xj = vs[j][0], yj = vs[j][1]; var intersect = ((yi > y) != (yj > y))
&& (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
if (intersect) inside = !inside;
} return inside;
};
//example:
var inside = require('point-in-polygon');
var polygon = [ [ 1, 1 ], [ 1, 2 ], [ 2, 2 ], [ 2, 1 ] ]; //左上, 右上, 右下, 左下 console.dir([
inside([ 1.5, 1.5 ], polygon),
inside([ 4.9, 1.2 ], polygon),
inside([ 1.8, 1.1 ], polygon)
]);
判断一个点是否在一个圆这内:
function pointInsideCircle(point, circle, r) {
if (r===0) return false
var dx = circle[0] - point[0]
var dy = circle[1] - point[1]
return dx * dx + dy * dy <= r * r
}