// 1 判断相交
//判断两多边形线段是否相交
function isSegmentsIntersectant(segA, segB) {//线线
const abc = (segA[0][0] - segB[0][0]) * (segA[1][1] - segB[0][1]) - (segA[0][1] - segB[0][1]) * (segA[1][0] - segB[0][0]);
const abd = (segA[0][0] - segB[1][0]) * (segA[1][1] - segB[1][1]) - (segA[0][1] - segB[1][1]) * (segA[1][0] - segB[1][0]);
if (abc * abd >= 0) {
return false;
}
const cda = (segB[0][0] - segA[0][0]) * (segB[1][1] - segA[0][1]) - (segB[0][1] - segA[0][1]) * (segB[1][0] - segA[0][0]);
const cdb = cda + abc - abd;
console.log("线段是否相交:", !(cda * cdb >= 0));
return !(cda * cdb >= 0);
}
function isPolygonsIntersectant(plyA, plyB) {//面面
for (let i = 0, il = plyA.length; i < il; i++) {
for (let j = 0, jl = plyB.length; j < jl; j++) {
const segA = [plyA[i], plyA[i === il - 1 ? 0 : i + 1]];
const segB = [plyB[j], plyB[j === jl - 1 ? 0 : j + 1]];
if (isSegmentsIntersectant(segA, segB)) {
console.log("边界相交:");
return true;
}
}
}
console.log("边界不相交:");
return false;
}
// 2 判断包含
//判断点是否在另一平面图中
function pointInPolygon(point, vs) {
// https://github.com/substack/point-in-polygon
const x = point[0], y = point[1];
let inside = false;
for (let i = 0, j = vs.length - 1; i < vs.length; j = i++) {
const xi = vs[i][0], yi = vs[i][1];
const xj = vs[j][0], yj = vs[j][1];
const intersect = ((yi > y) !== (yj > y))
&& (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
if (intersect) {
inside = !inside;
}
}
console.log(inside);
return inside;
}
//判断两多变形是否存在点与区域的包含关系(A的点在B的区域内或B的点在A的区域内)
function isPointInPolygonBidirectional(plyA, plyB) {//面面
let [a, b] = [false, false];
a = plyA.some(item => pointInPolygon(item, plyB));
if (!a) {
b = plyB.some(item => pointInPolygon(item, plyA));
}
console.log("包含关系:", a || b);
return a || b;
}
// 3 判断多边形是否重合
function isPolygonsOverlap(plyA, plyB) {
return isPolygonsIntersectant(plyA, plyB) || isPointInPolygonBidirectional(plyA, plyB);
}
// const plyA = [[109.12560386473433, 333.99033816425117],[367.90096618357484, 333.99033816425117],[239.1570048309178, 462.7342995169082]],
// plyB = [[122.78502415458934, 261.3623188405797],[187.1570048309178, 325.7342995169082],[122.78502415458934, 390.10628019323667]];
const plyA = [
[
90.703125,
67.47492238478702
],
[
87.1875,
67.06743335108298
],
[
81.5625,
50.958426723359935
],
[
46.7578125,
39.639537564366684
],
[
113.5546875,
39.095962936305476
],
[
130.78125,
67.06743335108298
],
[
90.703125,
67.47492238478702
]
]
plyB = [
[
75.5859375,
52.696361078274485
],
[
79.8046875,
67.60922060496382
],
[
29.179687499999996,
63.54855223203644
],
[
-1.7578125,
35.746512259918504
],
[
0.3515625,
4.214943141390651
],
[
51.67968749999999,
-13.2399454992863
],
[
56.25,
30.44867367928756
],
[
21.09375,
32.54681317351514
],
[
41.1328125,
44.84029065139799
],
[
75.5859375,
52.696361078274485
]
]
;
const isOver = isPolygonsOverlap(plyA, plyB);
console.log(isOver)