Skip to content

Instantly share code, notes, and snippets.

@jashkenas
Created November 5, 2012 03:50
Show Gist options
  • Save jashkenas/4015219 to your computer and use it in GitHub Desktop.
Save jashkenas/4015219 to your computer and use it in GitHub Desktop.
var intersect = function(a1, a2, b1, b2) {
var ua_t = (b2.x - b1.x) * (a1.y - b1.y) - (b2.y - b1.y) * (a1.x - b1.x);
var ub_t = (a2.x - a1.x) * (a1.y - b1.y) - (a2.y - a1.y) * (a1.x - b1.x);
var u_b = (b2.y - b1.y) * (a2.x - a1.x) - (b2.x - b1.x) * (a2.y - a1.y);
if ( u_b != 0 ) {
var ua = ua_t / u_b;
var ub = ub_t / u_b;
if ( 0 <= ua && ua <= 1 && 0 <= ub && ub <= 1 ) {
return {
x: a1.x + ua * (a2.x - a1.x),
y: a1.y + ua * (a2.y - a1.y)
};
} else {
throw "No Intersection";
}
} else {
if ( ua_t == 0 || ub_t == 0 ) {
throw "Coincident";
} else {
throw "Parallel";
}
}
};
@dvberkel
Copy link

dvberkel commented Nov 5, 2012

It seems you could benefit from a higher level of abstraction. Something along the lines of

var a = Line.through(a1, a2);
var b = Line.through(b1, b2);

if (!a.isParrallelTo(b)) {
  point = a.intersectWith(b);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment