Bresenham’s algorythm in javascript

With the advent of HTML5 and canvas, old game programming techniques are going to be unearthed and taken out of retirement, one such technique is called bresenhams algorythm.

Bresenham’s algorythm is a line drawing algorythm, basically it is more or less what lineTo does in html5 canvas. So why would want to use that when the browser does that for you?

Well the basic reason is that in games you have to have an internal representation of what the screen is doing, for example comparing two lines to see if they intersect; now with bresenham’s algorythm you compare two arrays for matching elements. and you can test whether a point is inside a box or a circle, or any shape that you can distinguish the shape of using maths.

    function bresenham(x1,y1,x2,y2){
            pts=[];

            // Initalize the math
            dx = x2 - x1;
            sx = (dx < 0) ? -1 : 1;
            dy = y2 - y1;
            sy = (dy < 0) ? -1 : 1;
            m = dy / dx;
            b = y1 - (m * x1);

            while((x1!=x2)&&(y1!=y2)){
               y = Math.round((m * x1) + b);
               pts.push({"x":x1,"y":y});
               x1 += (sx * 1);
            }
           
            return pts;
    };

The code above is an enhancement from this blog post

for a demo the actual code is making the green line. not the rest which is part of a future javascript game engine.

This entry was posted in Uncategorized by admin. Bookmark the permalink.

Comments are closed.