brezenhem

by Leo

HTML

<h4>Line drawn pixel-by-pixel with Bresenham's line algorithm</h4>
<canvas id="canvas" width=600 height=600></canvas>

CSS

body{ background-color: ivory; }
canvas{border:1px solid red;}

JavaScript

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

//=====================================================================
const step=30;
const N=20; 

bline(2, 2, 8, 8, step, ctx);


function updateCells(){
   ctx.strokeStyle = "#777777";
  
   for(var i = 0; i < N+1; i++)
   {
     ctx.beginPath();
     ctx.moveTo(i*step, 0);
     ctx.lineTo(i*step, N*step);
     ctx.stroke();
     
     ctx.beginPath();
     ctx.moveTo(0, i*step);
     ctx.lineTo(N*step, i*step);
     ctx.stroke();
   }
}

updateCells();


/* function setPixel(x, y, step) {
    var n = (y * canvas.width + x) * 4;
    data[n] = 0;
    data[n + 1] = 0;
    data[n + 2] = 255;
    data[n + 3] = 255;
} */

function setPixel(x, y, step, ctx) {
    ctx.fillStyle="#FF0000";
    ctx.fillRect(x*step,y*step,step,step);
} 

// Refer to: http://rosettacode.org/wiki/Bitmap/Bresenham's_line_algorithm#JavaScript
function bline(x0, y0, x1, y1, step, ctx) {
    var dx = Math.abs(x1 - x0),
        sx = x0 < x1 ? 1 : -1;
    var dy = Math.abs(y1 - y0),
        sy = y0 < y1 ? 1 : -1;
    var err = (dx > dy ? dx : -dy) / 2;
    while (true) {
        setPixel(x0, y0, step, ctx);
        if (x0 === x1 && y0 === y1) break;
        var e2 = err;
        if (e2 > -dx) {
            err -= dy;
            x0 += sx;
        }
        if (e2 < dy) {
            err += dx;
            y0 += sy;
        }
    }
}