我们有 2 条线。我们怎样才能得到那两条线与 JavaScript 相交的点?

We have 2 lines. How can we get point where that 2 lines intersect with JavaScript?

第一行A(x1,y1)为起点,B(x2,y2)为终点
第二行 A(x2,y2) 是起点,B(x2,y2) 是终点

我需要一个可以return这两条线相交点的函数。

这是一篇不错的读物: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)));