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=20;
const N=30;
const x0=1, y0=2, x1=8, y1=8
canvas.width=N*step;
canvas.height=N*step;
//fill approximated line
ctx.fillStyle="#77aa00";
bline(x0, y0, x1, y1, step, ctx);
//draw smooth line
ctx.strokeStyle = "#FF0000";
ctx.beginPath();
ctx.moveTo(x0*step, y0*step);
ctx.lineTo(x1*step, y1*step);
ctx.stroke();
//stroke axis cells
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();
}
function setPixel(x, y, step, ctx) {
ctx.fillStyle="#77aa00";
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;
}
}
}