Skip to content

Instantly share code, notes, and snippets.

@steveruizok
Created July 24, 2020 18:48
Show Gist options
  • Save steveruizok/9f02b0be4f852cebf699bb9d9bd4c833 to your computer and use it in GitHub Desktop.
Save steveruizok/9f02b0be4f852cebf699bb9d9bd4c833 to your computer and use it in GitHub Desktop.
Find the point at which one line segment intersects another.
function getSegmentSegmentIntersection(
x0: number,
y0: number,
x1: number,
y1: number,
x2: number,
y2: number,
x3: number,
y3: number
) {
const denom = (y3 - y2) * (x1 - x0) - (x3 - x2) * (y1 - y0);
const numeA = (x3 - x2) * (y0 - y2) - (y3 - y2) * (x0 - x2);
const numeB = (x1 - x0) * (y0 - y2) - (y1 - y0) * (x0 - x2);
if (denom === 0) {
if (numeA === 0 && numeB === 0) {
return undefined; // Colinear
}
return undefined; // Parallel
}
const uA = numeA / denom;
const uB = numeB / denom;
if (uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1) {
return [x0 + uA * (x1 - x0), y0 + uA * (y1 - y0)];
}
return undefined; // No intersection
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment