第一行A(x1,y1)是起点,B(x2,y2)是终点 第二行A(x2,y2)是起点,B(x2,y2)是终点 我需要一个函数,它可以使我们返回这两条线相交的点。 预先感谢
答案 0 :(得分:-1)
这是一本不错的读物:How to check if two given line segments intersect
这是使用JavaScript的一种方法:
var Point = function(valA, valB) {
this.x = valA;
this.y = valB;
};
function lineIntersection(pointA, pointB, pointC, pointD) {
var z1 = (pointA.x - pointB.x);
var z2 = (pointC.x - pointD.x);
var z3 = (pointA.y - pointB.y);
var z4 = (pointC.y - pointD.y);
var dist = z1 * z4 - z3 * z2;
if (dist == 0) {
return null;
}
var tempA = (pointA.x * pointB.y - pointA.y * pointB.x);
var tempB = (pointC.x * pointD.y - pointC.y * pointD.x);
var xCoor = (tempA * z2 - z1 * tempB) / dist;
var yCoor = (tempA * z4 - z3 * tempB) / dist;
if (xCoor < Math.min(pointA.x, pointB.x) || xCoor > Math.max(pointA.x, pointB.x) ||
xCoor < Math.min(pointC.x, pointD.x) || xCoor > Math.max(pointC.x, pointD.x)) {
return null;
}
if (yCoor < Math.min(pointA.y, pointB.y) || yCoor > Math.max(pointA.y, pointB.y) ||
yCoor < Math.min(pointC.y, pointD.y) || yCoor > Math.max(pointC.y, pointD.y)) {
return null;
}
return new Point(xCoor, yCoor);
}
console.log(lineIntersection(new Point(40, 0), new Point(180, 140), new Point(60, 120), new Point(180, 40)));