Skip to content

Instantly share code, notes, and snippets.

@williame
Last active August 29, 2015 14:07
Show Gist options
  • Save williame/494ed07fcadb53aebe9b to your computer and use it in GitHub Desktop.
Save williame/494ed07fcadb53aebe9b to your computer and use it in GitHub Desktop.
<html>
<head>
<meta charset="utf-8"/>
<title>WillLife</title>
<script type="text/javascript">
"use strict";
var canvas, src, dest, imgdata, width, height, dx = 3;
var sampler = [];
(function() {
var max = dx*dx*2;
for(var y=-dx; y<=dx; y++)
for(var x=-dx; x<=dx; x++)
sampler.push(1 - (y*y+x*x) / max);
})();
function score(x,y) {
var s = -src[y*width*4 + x*4], c = -1; // we'll visit the x,y cell so subtract it before we start
for(var i=y-dx; i<=y+dx; i++) {
if(i < 0 || i >= height)
continue;
for(var j=x-dx; j<=x+dx; j++) {
if(j < 0 || j >= width)
continue;
var d = sampler[Math.abs(i-y)*dx*2+Math.abs(j-x)];
s += src[i*width*4 + j*4] * d;
c += d;
}
}
return (s/c)|0;
}
function tick() {
for(var i=0, k=0; i<height; i++)
for(var j=0; j<width; j++, k += 4) {
var a = src[k], b = score(j, i);
var c = (a < b? a + 17: a - 7);
dest[k] = dest[k+1] = dest[k+2] = c;
}
var ctx = canvas.getContext("2d");
imgdata.data.set(dest);
ctx.putImageData(imgdata,0,0);
src.set(dest);
setTimeout(tick, 100);
}
function start() {
var img = document.getElementsByTagName("img")[0];
canvas = document.createElement("canvas");
width = canvas.innerWidth = canvas.width = img.width;
height = canvas.innerHeight = canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img,0,0);
var parent = img.parentNode;
parent.removeChild(img);
parent.appendChild(canvas);
imgdata = ctx.getImageData(0,0,width,height);
src = new Uint8Array(imgdata.data);
dest = new Uint8Array(imgdata.data);
setTimeout(tick, 100);
}
</script>
<body onload="start()">
<center><img src="mona.png"/></center>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment