Search code examples
javascriptfunctionlinepointsintersect

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


1st line A(x1, y1) is starting point and B(x2,y2) is end point
2st line A(x2,y2) is starting point and B(x2,y2) is end point

I need a function which can return the point where these 2 lines will intersect.


Solution

  • Here's a good read: How to check if two given line segments intersect

    and here's a way to do it using 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)));