Skip to content

Instantly share code, notes, and snippets.

@arcollector
Created May 4, 2015 00:06
Show Gist options
  • Save arcollector/36294d625d3f712c3c35 to your computer and use it in GitHub Desktop.
Save arcollector/36294d625d3f712c3c35 to your computer and use it in GitHub Desktop.
DDA Line drawing
function line( xa,ya, xb,yb ) {
dx = xb - xa;
dy = yb - ya;
if( dx < 0 ) {
cInc = -1;
} else {
cInc = 1;
}
if( dy < 0 ) {
rInc = -1;
} else {
rInc = 1;
}
if( Math.abs( dx ) >= Math.abs( dy ) ) {
m = dy / dx;
if( m < 0 ) {
m = -m;
}
h = 0;
c = xa;
r = ya;
console.log('plot',c,r);
for( i = Math.abs( dx ); i > 0; i-- ) {
c += cInc;
h += m;
if( h > .5 ) {
r += rInc;
h -= 1;
}
console.log('plot',c,r);
}
} else {
m = dx / dy;
if( m < 0 ) {
m = -m;
}
h = 0;
c = xa;
r = ya;
console.log('plot',c,r);
for( i = Math.abs( dy ); i > 0; i-- ) {
r += rInc;
h += m;
if( h >= .5 ) {
h -= 1;
c += cInc;
}
console.log('plot',c,r);
}
}
}
//line(8,3, 1,1);
//line(-7,3, -1,1);
//line(1,-1, 3,-6);
//line(-7,-2, -1,1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment