Points on Line

Pixel line

This method finds all the points or pixels touched by a line between the points x1, y1 and x2, y2, and returns the points as an array of coordinates.

View example

function pointsOnLine(x1, y1, x2, y2)
{
	line = new Array();

	var dx = Math.abs(x2 - x1);
	var dy = Math.abs(y2 - y1);
	var x = x1;
	var y = y1;
	var n = 1 + dx + dy;
	var xInc = (x1 < x2 ? 1 : -1);
	var yInc = (y1 < y2 ? 1 : -1);
	var error = dx - dy;

	dx *= 2;
	dy *= 2;

	while(n>0)
	{
		line.push([x, y]);

		if(error>0)
		{
			x+= xInc;
			error-= dy;
		}
		else
		{
			y+= yInc;
			error+= dx;
		}

		n-= 1;
	}

	return line;
}

Page loaded in 0.01 second(s).