Created
July 24, 2020 18:48
-
-
Save steveruizok/9f02b0be4f852cebf699bb9d9bd4c833 to your computer and use it in GitHub Desktop.
Find the point at which one line segment intersects another.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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