Each cell holds a value from 0-255 and has four neighbours. On each iteration, if the sum of all neighbours equals a given number ('the rule') the cell's value becomes 255. Otherwise it is decreased by 1 if it is greater than zero. If it's zero, then it stays as zero.
I've implemented it using HTML5 canvas, doing pixel-level access with
ImageData
.See it here. It works on the 'modern' browsers that I've tested; Firefox, Safari and Chrome. It ought to work on IE9 and above and maybe Opera.
A quick note on the implementation:
I created a 2d context for the canvas element
var canvas = document.getElementById("ccc");
var ctx = canvas.getContext("2d");
Then an ImageData
to cover the whole canvas.
var imd = ctx.createImageData(canvas.width,canvas.height);
I drew the image with
ctx.putImageData(imd, 0, 0);
I didn't work directly with the ImageData
's data, which is always in 32-bit RGBA format. Instead I created a Uint8Array
with 8 bits per pixel (I only needed to store 0-255), then converted it to image format as follows
function convi(imd, data) {
var i;
var out = imd.data;
for (i=0; i<data.length; ++i) {
out[i*4] = out[i*4+1] = out[i*4+2] = data[i];
out[i*4+3] = 255;
}
}
I just converted the 0-255 to a greyscale but here would be the place to implement a colour look-up table and get a nice palette.
No comments:
Post a Comment