Create an Account
username: password:
 
  MemeStreams Logo

MemeStreams Discussion

search


This page contains all of the posts and discussion on MemeStreams referencing the following web page: Bresenham's line algorithm. You can find discussions on MemeStreams as you surf the web, even if you aren't a MemeStreams member, using the Threads Bookmarklet.

Bresenham's line algorithm
by Acidus at 5:08 am EST, Feb 18, 2008
DrawingSpace.prototype.drawLine = function(x0,y0,x1,y1) {

    var steep = Math.abs(y1 - y0) > Math.abs(x1 - x0);
    var tmp = 0;
 
    if(steep) {
        //swap(x0, y0)
        tmp = y0;
        y0 = x0;
        x0 = tmp;
        //swap(x1, y1)
        tmp = y1;
        y1 = x1;
        x1 = tmp;
    }
    if(x0 > x1) {
        //swap(x0, x1)
        tmp = x1;
        x1 = x0;
        x0 = tmp;
        //swap(y0, y1)
        tmp = y0;
        y0 = y1;
        y1 = tmp;    
    }
    
    var deltax = x1 - x0;
    var deltay = Math.abs(y1 - y0)
    var error = -(deltax + 1) / 2
    var ystep;
    
    var y = y0;
    if(y0 < y1) {
        ystep = 1;
    } else {
        ystep = -1;
    }
    
    for(var x = x0; x <=x1; x++) {
        if(steep) {
            this.buffer.setXY(y,x);
        } else {
            this.buffer.setXY(x,y);
        }
        error += deltay;
        if(error >=0) {
            y += ystep;
            error -=deltax;
        }
    }

}

Now why would you ever need an integer optimized line drawing algorithm in JavaScript? :-)


 
 
Powered By Industrial Memetics