Line intersection

Lines crossing test

A simple function for testing if two lines on a 2D plane cross one another. If they do, the coordinates at which they meet or cross are returned, otherwise the function returns false.

View example

function lineIntersection(l1, l2)
{
	var s1 = [0,0], s2 = [0,0];
	s1[0] = l1[1][0] - l1[0][0];
	s1[1] = l1[1][1] - l1[0][1];

	s2[0] = l2[1][0] - l2[0][0];
	s2[1] = l2[1][1] - l2[0][1];

	var s = (-s1[1] * (l1[0][0] - l2[0][0]) + s1[0] * (l1[0][1] - l2[0][1])) / (-s2[0] * s1[1] + s1[0] * s2[1]);
	var t = ( s2[0] * (l1[0][1] - l2[0][1]) - s2[1] * (l1[0][0] - l2[0][0])) / (-s2[0] * s1[1] + s1[0] * s2[1]);

	if(s >= 0 && s <= 1 && t >= 0 && t <= 1)
	{
		return [l1[0][0] + (t * s1[0]),
			l1[0][1] + (t * s1[1])];
	}

	return false;
}

Page loaded in 0.01 second(s).