Intersection between two lines

2012-09-11

Simple way of getting the point of intersection between two lines (A-AA and B-BB) on a (2d) plane.

Pass on the xy coordinates for all end points of the lines and you'll either get an object with x/y back or the falsy value null.

Not my math by the way. Got it from stackoverflow, where else.

Code:
function intersects(ax, ay, aax, aay, bx, by, bbx, bby){
var sax = aax - ax;
var say = aay - ay;
var sbx = bbx - bx;
var sby = bby - by;

var s = (-say * (ax - bx) + sax * (ay - by)) / (-sbx * say + sax * sby);
var t = ( sbx * (ay - by) - sby * (ax - bx)) / (-sbx * say + sax * sby);

if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
var x = ax + (t*sax);
var y = ay + (t*say);

return {x:x, y:y};
}

return null;
}

Interactive demo

Hope it helps ya :)