Chaos game square

by Jonathan Lam

HTML

<canvas width="1920" height="1920" id="canvas"></canvas>

JavaScript

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;

var iterations = 1e6;

var pointer = {
	x: Math.random() * width,
  y: Math.random() * height
};
var corners = [
	{x: 0, y: 0},
  {x: 0, y: height},
  {x: width, y: height},
  {x: width, y: 0}
];
function mod(n, m) {
  return ((n % m) + m) % m;
}
var restriction = function() {
	//console.log(cornerId, lastCornerId, cornerId %2, lastCornerId %2, cornerId%2 !== lastCornerId%2)
	return lastCornerId === null || 
  //cornerId !== lastCornerId;
  //mod(cornerId+1, 4) !== lastCornerId;
  //(mod(lastCornerId+2, 4) !== cornerId);
  (secondLastCornerId === null || thirdLastCornerId === null ||
  	!((lastCornerId+2)%4 === cornerId && (thirdLastCornerId+2)%4 !== cornerId)
  );
  /*(secondLastCornerId === null || 
  	(
    	((lastCornerId+2)%4 !== cornerId) ||
      ((secondLastCornerId+2)%4 !== cornerId)
    )
  );*/
  /*(secondLastCornerId === null || 
  	(
    	((lastCornerId+1)%4 === cornerId || mod(lastCornerId-1, 4) === cornerId) ||
      ((secondLastCornerId+3)%4 === cornerId || mod(secondLastCornerId-3, 4) === cornerId)
    )
  );*/
};
var cornerId = null;
var lastCornerId = null;
var secondLastCornerId = null;
var thirdLastCornerId = null;
for(var i = 0; i < iterations; i++) {
  cornerId = Math.floor(Math.random()*4);
  if(restriction()) {
  	var corner = corners[cornerId];
    pointer.x = (pointer.x + corner.x)/2;
    pointer.y = (pointer.y + corner.y)/2;
    ctx.fillRect(pointer.x, pointer.y, 1, 1);
    thirdLastCornerId = secondLastCornerId;
    secondLastCornerId = lastCornerId;
    lastCornerId = cornerId;
  } else {
  	//i--;
  }
}