Hi all, I’ve just found a Javascript implementation of the Bresenham’s line algorithm and I’m just trying to understand what it’s actually doing and was wondering whether anybody would mind giving me a brief explanation about a few lines of it.
Here’s the algorithm itself:
function renderLine(x0, y0, x1, y1) {
var xx0 = x0;
var yy0 = y0;
var xx1 = x1;
var yy1 = y1;
var dx = Math.abs(xx1 - xx0);
var dy = Math.abs(yy1 - yy0);
var stepx, stepy;
if(xx0 < xx1) stepx = 1;
else stepx = -1;
if(yy0 < yy1) stepy = 1;
else stepy = -1;
var err = dx - dy;
while(true) {
renderPoint(xx0, yy0);
if(xx0 == xx1 && yy0 == yy1) break;
[b]var e2 = err << 1;
if(e2 > -dy) {
err -= dy;
xx0 += stepx;
}
if(e2 < dx) {
err += dx;
yy0 += stepy;
}[/b]
}
}
The section I’m having difficulty getting my head around is emboldened. I understand from reading the wikipedia page on the different methods of implementing it that you create an error variable and loop through every value between the two points X components, then you add the slope of the line to the error until it reaches over 0.5 and then you increase the Y component and subtract 1 from the error. I also understand that this is more or less what’s happening above using integer arithmetic rather than floating point arithmetic although I’m not entirely sure why error needs to be multiplied by 2 or what the significance of this being over -dy or under dx is. Forgive my noobiness - I’m just stuck with this. If anyone could explain this I’d be grateful.
Thanks