Skip to content

Instantly share code, notes, and snippets.

@BriSeven
Created April 29, 2016 09:30
Show Gist options
  • Save BriSeven/725cfe7863ed34621cf06e7fa9663821 to your computer and use it in GitHub Desktop.
Save BriSeven/725cfe7863ed34621cf06e7fa9663821 to your computer and use it in GitHub Desktop.
// integer part of x
function ipart(x) {
return Math.floor(x);
}
function round(x) {
return Math.round(x);
}
// fractional part of x
function fpart(x) {
return x - Math.floor(x);
}
function rfpart(x) {
return 1 - fpart(x);
}
function plot(x, y, c) {
x=x|0;
y=y|0;
// plot the pixel at (x, y) with brightness c (where 0 ≤ c ≤ 1)
ctx.fillStyle="rgba(0,0,0,{{c}})".hairlip({c:(c)});
ctx.fillRect(x*pxSize, y*pxSize, pxSize, pxSize);
}
function plotPair (x, y, weight, steep, xgap) {
if(steep) {
plot(y , x, xgap * (1 - weight));
plot(y + 1, x, xgap * weight);
} else {
plot(x, y , xgap * (1 - weight));
plot(x, y+1, xgap * weight);
}
}
//generate an array of input for plotpair
var lookuptable = {};
function makeLineIterator(x0,y0,x1,y1){
var steep = Math.abs(y1 - y0) > Math.abs(x1 - x0);
function midpoint(xp1, x, y, slope, steep, xgap) {
var xint = round(x);
var yint = y + slope * ( xint - xp1 );
return [ xint, ipart(yint), fpart(yint), steep, xgap]
}
function makeSublineIterator(x0,y0,x1,y1,steep) {
var slope = (y1 - y0) / (x1 - x0);
var intery = slope * (round(x0) - x0) + slope + y0 // first y-intersection for the main loop
var xp1 = round(x0);
var xp2 = round(x1);
var x = xp1-1;
return {
next: function() {
x+=1;
if (x === xp1) return {value: midpoint( xp1, x0, y0, slope, steep, rfpart(x0 + 0.5) ), done: false};
if (x > xp1 && x < xp2) return {value: midpoint( xp1+1, x, intery, slope, steep, 1 ), done: false};
if (x === xp2) return {value: midpoint( xp2, x1, y1, slope, steep, fpart(x1 + 0.5) ), done: false};
if (x > xp2) return {done: true};
}
}
}
return steep ?
y0 > y1 ?
makeSublineIterator(y1,x1,y0,x0,steep) :
makeSublineIterator(y0,x0,y1,x1,steep) :
x0 > x1 ?
makeSublineIterator(x1,y1,x0,y0,steep) :
makeSublineIterator(x0,y0,x1,y1,steep)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment