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
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.