Test if two lines intersect - JavaScript function

前端 未结 10 1567
谎友^
谎友^ 2020-12-02 09:08

I\'ve tried searching for a javascript function that will detect if two lines intersect each other.

The function will take the x,y values of both the start end point

10条回答
  •  我在风中等你
    2020-12-02 09:54

    Here comes a TypeScript implementation, heavily inspired by Dan Fox's solution. This implementation will give you the intersection point, if there is one. Otherwise (parallel or no intersection), undefined will be returned.

    interface Point2D {
      x: number;
      y: number;
    }
    
    function intersection(from1: Point2D, to1: Point2D, from2: Point2D, to2: Point2D): Point2D {
      const dX: number = to1.x - from1.x;
      const dY: number = to1.y - from1.y;
    
      const determinant: number = dX * (to2.y - from2.y) - (to2.x - from2.x) * dY;
      if (determinant === 0) return undefined; // parallel lines
    
      const lambda: number = ((to2.y - from2.y) * (to2.x - from1.x) + (from2.x - to2.x) * (to2.y - from1.y)) / determinant;
      const gamma: number = ((from1.y - to1.y) * (to2.x - from1.x) + dX * (to2.y - from1.y)) / determinant;
    
      // check if there is an intersection
      if (!(0 <= lambda && lambda <= 1) || !(0 <= gamma && gamma <= 1)) return undefined;
    
      return {
        x: from1.x + lambda * dX,
        y: from1.y + lambda * dY,
      };
    }
    

提交回复
热议问题