moireelines

by 386dx25

HTML

<html>

  <body>
    <canvas id="moireelines" width="128" height="128"></canvas>
  </body>

</html>

CSS

#moireelines {
  image-rendering: pixelated;
  width: 100%;
  max-width: 512px;
  border: solid 1px black;
}

JavaScript

const canvas = document.getElementById('moireelines');
const ctx = canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;

var data = null;

function pset(x,y) {
	const ofs = (y*width + x) * 4;
  data[ofs] = data[ofs + 1] = data[ofs + 2] = 128;
  data[ofs + 3] = 255;
}

function psetxor(x,y) {
	const ofs = (y*width + x) * 4;
  const value = data[ofs];
  data[ofs] = data[ofs + 1] = data[ofs + 2] = value ^ 196;
  data[ofs + 3] = 255;
}

function line(x0,y0,x1,y1) {
  const dx = x1 - x0;
  const dy = y1 - y0;
  if(Math.abs(dy/dx)<=1) {
  	const m =  dy / dx;
    let step = 0.0;
    for(let i=0; i < Math.abs(dx); i++) {
    	let x = x0 + Math.sign(dx)*i;
      psetxor(x, y0 + Math.round(step));
      step += m;
    }  
  } else {
  	const m =  dx / dy;
    let step = 0.0;
    for(let i=0; i < Math.abs(dy); i++) {
    	let y = y0 + Math.sign(dy)*i;
      psetxor(x0 + Math.round(step), y);
      step += m;
    }    
  }
}

function draw() {
  const buffer = ctx.getImageData(0, 0, width, height);
	data = buffer.data;
  
  for(let x=2; x < width; x+=1) {
    line(x, 0, 0, height);
    line(0, height, width, x);
  	//line(x, 0, width/2, height/2);
    //line(width/2, height/2, x, height);
  	//line(0, y, width/2, height/2);
  	//line(width-x-1, height, x, 0);
  }
  
  if(false) {
    const h = Math.floor(height/2);
    line(0,h, width-1,h);

    const h3 = Math.floor(2.0*height/3.0);
    line(0,h3, width-1,h3);

    const h4 = Math.floor(3.0*height/4.0);
    line(0,h4, width-1,h4);  
  }

  ctx.putImageData(buffer, 0, 0);
}

draw();