Created
September 23, 2018 20:30
-
-
Save jiayihu/48e4f5cf8710374288422de67a6e5b23 to your computer and use it in GitHub Desktop.
Determine the intersection point of two line segments, but considering also colinear segments as intersection
This file contains 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
/** | |
* Determine the intersection point of two line segments, but considering also | |
* colinear segments as intersection | |
* @see {@link http://paulbourke.net/geometry/pointlineplane/} | |
*/ | |
function intersect( | |
x1, y1, x2, y2, | |
x3, y3, x4, y4 | |
) { | |
// Check if none of the lines are of length 0 | |
if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) { | |
return null | |
} | |
const denominator = ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)) | |
const numera = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) | |
const numerb = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) | |
// Lines are parallel | |
if (denominator === 0) { | |
const isColinear = numera === 0 && numerb === 0; | |
return isColinear ? Infinity : null | |
} | |
const ua = numera / denominator | |
const ub = numerb / denominator | |
// is the intersection along the segments | |
if ((ua >= 0 && ua <= 1) && (ub >= 0 && ub <= 1) ) { | |
// Intersection point | |
const x = x1 + ua * (x2 - x1) | |
const y = y1 + ua * (y2 - y1) | |
return { x, y } | |
} | |
return null | |
} | |
const segmentIntersection = intersect(0, 0, 1, 1, 0, 1, 1, 0) // { x: 0.5, y: 0.5 } | |
const parallel = intersect(0, 0, 1, 0, 0, 1, 1, 1) // null | |
const lineIntersection = intersect(0, 0, 1, 1, 0, 3, 2, 2) // null | |
const edge = intersect(0, 0, 1, 1, 0, 3, 1, 1) // { x: 1, y: 1 } | |
const colinear = intersect(0, 0, 2, 0, 1, 0, 2, 0) // true | |
console.log({ | |
segmentIntersection, | |
parallel, | |
lineIntersection, | |
edge, | |
colinear | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment