Skip to content

Instantly share code, notes, and snippets.

@werelax
Created March 22, 2014 19:23
Show Gist options
  • Save werelax/9712818 to your computer and use it in GitHub Desktop.
Save werelax/9712818 to your computer and use it in GitHub Desktop.
Segments intersection
function segmentIntersection(a, b) {
var denom = (((b[1].y - b[0].y) * (a[1].x - a[0].x)) -
((b[1].x - b[0].x) * (a[1].y - a[0].y)));
if (denom === 0) { return null; }
var ua = ((((b[1].x - b[0].x) * (a[0].y - b[0].y)) -
((b[1].y - b[0].y) * (a[0].x -b[0].x))) / denom);
var ub = ((((a[1].x - a[0].x) * (a[0].y - b[0].y)) -
((a[1].y - a[0].y) * (a[0].x - b[0].x))) / denom);
if ((ua < 0) || (ua > 1) || (ub < 0) || (ub > 1)) { return null; }
return {
x: a[0].x + (ua * (a[1].x - a[0].x)),
y: a[0].y + (ua * (a[1].y - a[0].y))
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment