Skip to content

Instantly share code, notes, and snippets.

@arcollector
Last active August 29, 2015 14:20
Show Gist options
  • Save arcollector/37b481ca044092881e4c to your computer and use it in GitHub Desktop.
Save arcollector/37b481ca044092881e4c to your computer and use it in GitHub Desktop.
Integer DDA Line drawing in JS
function vLine( ya,yb, xa ) {
ya = Math.round( ya );
yb = Math.round( yb );
xa = Math.round( xa );
var y = ya < yb ? ya : yb,
i = Math.abs( ya - yb );
for( ; i >= 0; i-- ) {
console.log( 'plot', xa, y+i );
}
}
function hLine( xa,xb, ya ) {
xa = Math.round( xa );
xb = Math.round( xb );
ya = Math.round( ya );
var x = xa < xb ? xa : xb,
i = Math.abs( xa - xb );
for( ; i >= 0; i-- ) {
console.log( 'plot', x+i, ya );
}
}
function line( xa,ya, xb,yb ) {
xa = Math.round( xa );
ya = Math.round( ya );
xb = Math.round( xb );
yb = Math.round( yb );
var dx = xb - xa,
dy = yb - ya,
cInc, rInc,
h, i;
if( dx === 0 ) {
vLine( ya,yb, xa );
return;
} else if( dy === 0 ) {
hLine( xa,xb, ya );
return;
}
cInc = dx < 0 ? -1 : 1;
rInc = dy < 0 ? -1 : 1;
dx = Math.abs( dx );
dy = Math.abs( dy );
if( dx >= dy ) {
h = -dx;
console.log('plot',xa,ya);
for( i = dx; i > 0; i-- ) {
xa += cInc;
h += 2*dy;
if( h >= 0 ) {
ya += rInc;
h -= 2*dx;
}
console.log('plot',xa,ya);
}
} else {
h = -dy;
console.log('plot',xa,ya);
for( i = dy; i > 0; i-- ) {
ya += rInc;
h += 2*dx;
if( h >= 0 ) {
xa += cInc;
h -= 2*dy;
}
console.log('plot',xa,ya);
}
}
}
//line(8,3, 1,1);
//line(-7,3, -1,1);
//line(1,-1, 3,-6);
//line(-7,-2, -1,1);
//line(0,0,10,0);
//line(7,1, 1,3);
//line(1,1,1,10);
//line(1,1,1,1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment