calculating the point of intersection of two lines

前端 未结 5 1191
栀梦
栀梦 2020-12-05 21:16

I have dynamically generated lines that animate and I want to detect when a lines hits another. I\'m trying to implement some basic linear algebra to obtain the equation of

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 22:12

    There is an npm module that does just that: line-intersect.

    Install it using

    npm install --save line-intersect
    

    ES6 usage:

    import { checkIntersection } from "line-intersect";
    
    const result = lineIntersect.checkIntersection(
      line1.start.x, line1.start.y, line1.end.x, line1.end.y,
      line2.start.x, line2.start.y, line2.end.x, line2.end.y
    );
    
    result.type  // any of "none", "parallel", "colinear", "intersecting"
    result.point // only exists when result.type == 'intersecting'
    

    If you're using typescript, here are the typings:

    declare module "line-intersect" {
      export function checkIntersection(
        x1: number, y1: number,
        x2: number, y2: number,
        x3: number, y3: number,
        x4: number, y4: number): {
            type: string,
            point: {x:number, y:number}
        }; 
    }
    

    Put it in a file and reference if in tsconfig.json's "files" section.

提交回复
热议问题