Photo-Life

by Ruslan Alikberov

HTML

<body onload='onload()'>
<canvas id=World_1 width=64 height=64></canvas>

<canvas id=World_2 width=64 height=64></canvas>
<img id=View width=512 height=512 />
</body>

JavaScript

var	SHIFT = 5;

var	Worlds	= [];

function getcell(spc, x, y, col) {
	pix = spc.ctx.getImageData(x, y, 1, 1);
	if(isFinite(col)) {
		pix.data[0] = pix.data[1] = pix.data[2] = col ? 255 : 0;
		return spc.ctx.putImageData(pix, x, y);
	}
	return ((pix.data[0] | pix.data[1] | pix.data[2]) >> 6) & SHIFT;
}

function animate_space(dst, src, oth) {
	var	dx = [-1, -1, -1, +0, +1, +1, +1, +0];
	var	dy = [-1, +0, +1, -1, +1, -1, +0, +1];
	var	x, y, tx, ty;
	var	mx, my;
	var	i, s, c, t;
	var	setup = [];
	mx = dst.ctx.canvas.width;
	my = dst.ctx.canvas.height;
	for(y = 0; y < my; ++ y)
		for(x = 0; x < mx; ++ x) {
			s = 0;
			for(i = 0; i < 8; ++ i) {
				tx = x + dx[i];
				ty = y + dy[i];
				if(tx >= 0 && tx <= mx && ty >= 0 && ty <= my) {
					s += getcell(src, tx, ty);
				}
			}
			if(s < 2 || s > 3)
				getcell(dst, x, y, 0);
			else
			if(s == 3)
				getcell(dst, x, y, 1);
		}
}
var	Img;
function onload() {
  let imageURL = "https://cdn.glitch.com/4c9ebeb9-8b9a-4adc-ad0a-238d9ae00bb5%2Fmdn_logo-only_color.svg?1535749917189";

  Img = new Image;
  Img.crossOrigin = "Anonymous";
  Img.addEventListener("load", function(im) {main(Img)}, false);
  Img.src = imageURL;
}

function prepare_space(cnv, tags, im) {
	var	ctx = cnv.getContext("2d");
	var	space = [];
	var	src = "1";
	//
	ctx.fillStyle = "white";
	ctx.fillRect(0, 0, cnv.width, cnv.height);
	ctx.drawImage(im, 0, 0);
	Worlds.push({
		ctx	:ctx,
		space	:space
	});
}

function evolution(flag) {
	animate_space(Worlds[+flag & 1], Worlds[(+flag & 1) ^ 1]);
	document.getElementById("View").src = Worlds[+flag & 1].ctx.canvas.toDataURL();
	setTimeout("evolution(" + ((+flag & 1) ^ 1) + ")", 100);
}
var	Cells1 = "0,1 1,1 2,1 35;26 33,35 34,35 35,35 36,35 37,35 38,35 39,35 40,35 41,35 42,35 43,35 44,35 45,35 46,35 47,35";
var	Cells2 = "0;1 30,31 31,31 32,31 33,31 34,31 35,31 36,31 37,31 38,31 39,31 40,31";

function main(im) {
	prepare_space(document.getElementById("World_1"), Cells1.split(" "),...