这更像是一个数学问题而不是 JS 问题,但我希望你能帮助我。
我正在尝试围绕多边形创建航点。它应该能够走在一条线上。我需要观察以下情况(真意味着不可能):
在我的脚本中,我无法同时观察案例 2 和案例 7。多边形是一个数组,其中包含 5 个对象(点)。A 和 B 是红线的点。在这里你可以找到我的jsFiddle。
// check if point is in polygon
var intersectLinePolygon = function(A, B, poly){
var result = false;
for (var i = 0; i < poly.length; i++){
var C = { 'x':poly[i].x, 'y':poly[i].y };
var D = {};
// if it's not the last point, take the next
if (i != poly.length-1){ D.x = poly[i+1].x; D.y = poly[i+1].y; }
// if it's the last point, take the first
else { D.x = poly[0].x; D.y = poly[0].y; }
if (intersectLineLine(A, B, C, D)){ result = true; }
}
return result;
};
// check if there is an intersection between two lines
var intersectLineLine = function(A, B, C, D){
if (
(B.x == C.x && B.y == C.y) ||
(B.x == D.x && B.y == D.y) ||
(A.x == C.x && A.y == C.y) ||
(A.x == D.x && A.y == D.y)
){ return false; }
else { return (ccw(A,C,D) != ccw(B,C,D) && ccw(A,B,C) != ccw(A,B,D)); }
};
// helper function for intersectLineLine
var ccw = function(A, B, C){ return ((C.y-A.y)*(B.x-A.x) > (B.y-A.y)*(C.x-A.x)); };