Open xinglie opened 1 year ago
function isPointInPolygon(point, polygon) {
let x = point.x, y = point.y;
let inside = false;
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
let xi = polygon[i].x, yi = polygon[i].y;
let xj = polygon[j].x, yj = polygon[j].y;
let intersect = ((yi > y) != (yj > y))
&& (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
if (intersect) inside = !inside;
}
return inside;
}
// Example usage:
const point = {x: 3, y: 4};
const polygon = [{x: 1, y: 1}, {x: 5, y: 1}, {x: 5, y: 5}, {x: 1, y: 5}];
console.log(isPointInPolygon(point, polygon)); // O