Like this (it's not accurate)
How can I change the Bresenham line algorithm to keep cycling into itself and create this effect: (Drawning not accurate)
I have the basic line with 2 coordinates:
drawBresenhamLine = function (x0, y0, x1, y1) {
var dx, dy, e2, err, sx, sy;
console.log('Called LBR : ' + x0 + ',' + y0 + '->' + x1 + ',' + y1);
dx = Math.abs(x1 - x0);
sx = x0 < x1 ? 1 : -1;
dy = Math.abs(y1 - y0);
sy = y0 < y1 ? 1 : -1;
err = (dx > dy ? dx : -dy) / 2;
while (true) {
//console.log('Push : '+x0 +' ,'+ y0);
setPixel(x0, y0);
setEnd(x1,y1);
if (x0 === x1 && y0 === y1) {
break;
}
e2 = err;
if (e2 > -dx) {
err -= dy;
x0 += sx;
}
if (e2 < dy) {
err += dx;
y0 += sy;
}
}
return null;
};
setPixel(x,y)
changes the current pixel and drawBresenhamLine
will use its coords next iteration.
Suppose you have two variables defining the size of your canvas: canvasWidth
and canvasHeight
. Whenever you increment x or y just test against these variables:
if (e2 > -dx) {
err -= dy;
x0 += sx;
// check against sides of canvas:
if(x0 >= canvasWidth)
x0 = 0;
else if(x0 < 0)
x0 = canvasWidth - 1;
}
if (e2 < dy) {
err += dx;
y0 += sy;
// check against top and bottom of canvas:
if(y0 >= canvasHeight)
y0 = 0;
else if(y0 < 0)
y0 = canvasHeight - 1;
}
This assumes that the minimum x and y values are 0. If not then you can define a min and max x and y defining your canvas extent and test against those instead.