Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@yurydelendik
Created May 21, 2012 03:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yurydelendik/2760454 to your computer and use it in GitHub Desktop.
Save yurydelendik/2760454 to your computer and use it in GitHub Desktop.
getLineLineIntersection
var epsilon = 1e-8;
function getLineLineIntersection(x1, y1, x2, y2, x3, y3, x4, y4, collinearity) {
// creating coefficients for lines in the form: a * x + b + y = c
var a1 = -(y2 - y1), b1 = (x2 - x1), c1 = (x2 - x1) * y1 - (y2 - y1) * x1;
var a2 = -(y4 - y3), b2 = (x4 - x3), c2 = (x4 - x3) * y3 - (y4 - y3) * x3;
// finding the intersection
var d = a1 * b2 - a2 * b1;
if (d == 0) {
// two lines are parallel to each other
if (!collinearity || (x2 - x3) * (y2 - y1) != (y2 - y3) * (x2 - x1))
return null; // not interested in the segment or the points are not collinear
// finding solution for t in the line in the form: x = (x1 - x0) * t + x0
var t1 = x3 != x4 ? (x1 - x3) / (x4 - x3) : (y1 - y3) / (y4 - y3);
var t2 = x3 != x4 ? (x2 - x3) / (x4 - x3) : (y2 - y3) / (y4 - y3);
if ((t1 < 0 && t2 < 0) || (t1 > 1 && t2 > 1))
return null; // points 1 and 2 are outside the points 3 and 4 segment
// clamping t's to [0, 1] range
t1 = t1 < 0 ? 0 : t1 > 1 ? 1 : t1;
t2 = t2 < 0 ? 0 : t2 > 1 ? 1 : t2;
return [(x4 - x3) * t1 + x3, (y4 - y3) * t1 + y3,
(x4 - x3) * t2 + x3, (y4 - y3) * t2 + y3];
} else {
// calculating intersection point
var x = (c1 * b2 - c2 * b1) / d;
var y = (a1 * c2 - a2 * c1) / d;
// checking if the point belong to the both segments
if (x < Math.min(x1, x2) - epsilon || Math.max(x1, x2) + epsilon < x ||
y < Math.min(y1, y2) - epsilon || Math.max(y1, y2) + epsilon < y ||
x < Math.min(x3, x4) - epsilon || Math.max(x3, x4) + epsilon < x ||
y < Math.min(y3, y4) - epsilon || Math.max(y3, y4) + epsilon < y)
return null;
return [x, y];
}
}
console.log(getLineLineIntersection(0, 0, 2, 0, 0, 10, 2, 10));
console.log(getLineLineIntersection(0, 0, 2, 0, 0, 10, 2, -20));
console.log(getLineLineIntersection(0, 0, 0, 10, 0, 5, 0, 15, true));
console.log(getLineLineIntersection(208,320.65,208,336.84, 208,327.77777777777777,192,332.22222222222223));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment