JS 射線法 判斷點是否在多邊形內部

西瓜霜發表於2024-06-12
function pointInPolygon(point, polygon) {
  var x = point[0];
  var y = point[1];
  var inside = false;
  for (var i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
    var xi = polygon[i][0];
    var yi = polygon[i][1];
    var xj = polygon[j][0];
    var yj = polygon[j][1];
    var intersect = ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
    if (intersect) inside = !inside;
  }
  return inside;
}

// 使用示例
var pointA = [1, 1];
var polygonB = [[0, 0], [0, 2], [2, 2], [2, 0]];
var result = pointInPolygon(pointA, polygonB);
console.log(result); // 輸出 true 或 false

 

相關文章