Code for drawing a line using Bresenham algorithm in Javascript

Here is the snippet for drawing a line in javascript.

function drawline(xa,ya,xb,yb){
    var dx=Math.abs(xa-xb);
    var dy=Math.abs(ya-yb);
    var p=2*dy-dx;
    var twody=2*dy;
    var twodydx=2*(dy-dx);
    var x,y,xend;

    if(xa>xb)
    {
        x=xb;
        y=yb;
        xend=xa;
    }
    else
    {
        x=xa;
        y=yb;
        xend=xb;
    }
    drawpix(x,y);
    while(x<xend)
    {
        x++;
        if(p<0)
        {
            p+=twody;
        }
        else
        {
            y++;
            p+=twodydx;
        }
        drawpix(x,y);
    }
}

As in previous blog you can find the code for pixel drawing code. Here is the link for the pixel drawing code. http://bit.ly/Wzm0xG

Go through it and happy coding… Smile

Advertisements

4 comments

  1. Hi there! Your code have a mistake:


    if(xa>xb)
    {
    x=xb;
    y=yb;
    xend=xa;
    }
    else
    {
    x=xa;
    y=yb; <<<<<<<<<<<<<< This should be ya
    xend=xb;
    }

    And thanks for sharing this code, once corrected works like a charm 😀

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s