应用场景
多段线上找到能被投影的线段
已知条件:
线段两端点坐标:P1[x1, y1]、P2[x2, y2]
目标点:P[x0,y0]
思路
- 直接求出投影点,然后判断投影点是否在P1P2之间
-
求向量P1P2和P1P、P2P1和P2P的夹角。若有一个为钝角,则在线段外面
QQ截图20200324165727.png
代码
function isPointInsideSegment(x0, y0, x1, y1, x2, y2) {
// 求Cos∠PP1P2
let dx10, dy10, m10, dx12, dy12, m12;
dx10 = x0 - x1;
dy10 = y0 - y1;
m10 = Math.hypot(dx10, dy10);
dx12 = x2 - x1;
dy12 = y2 - y1;
m12 = Math.hypot(dx12, dy12);
if ((dx10 * dx12 + dy10 * dy12) / m10 / m12 < 0) return false;
// 求Cos∠PP2P1
let dx20, dy20, m20, dx21, dy21, m21;
dx20 = x0 - x2;
dy20 = y0 - y2;
m20 = Math.hypot(dx20, dy20);
dx21 = x1 - x2;
dy21 = y1 - y2;
m21 = Math.hypot(dx21, dy21);
return (dx20 * dx21 + dy20 * dy21) / m20 / m21 >= 0;
}
网友评论