Pages

Tuesday 18 January 2011

First Canvas Experiment: BitmapData

Lots of people have been talking about html 5 and canvas for a while now. As an actionscript purist I had decided not to venture into the world of incompatibility quite yet, but having seen some of the cool chrome experiments again recently, I decided to give writing some canvas toys a little go.

My first experiment is a simple one, just some randomly updating pixels on a screen.

Your browser doesn't support html5
Here is the .js code:
function setPixel(bitmapData, x, y, r, g, b, a) {
index = (x + y * bitmapData.width) * 4;
bitmapData.data[index+0] = r;
bitmapData.data[index+1] = g;
bitmapData.data[index+2] = b;
bitmapData.data[index+3] = a;
}

element = document.getElementById("bitmap");
canvas = element.getContext("2d");
width = parseInt(element.getAttribute("width"));
height = parseInt(element.getAttribute("height"));

setInterval('update()',30);

function update()
{
bitmap = canvas.createImageData(width,height);
for (i = 0; i < 10000; i++) {
     x = parseInt(Math.random() * width);
     y = parseInt(Math.random() * height);
     r = parseInt(Math.random() * 256);
     g = parseInt(Math.random() * 256);
     b = parseInt(Math.random() * 256);
     setPixel(bitmap, x, y, r, g, b, 0xff);
 }
 canvas.putImageData(bitmap, 0, 0);
}

No comments:

Post a Comment