Here’s some base code for simple canvas animations:
// get canvas element
var canvas = document.getElementById('canvas');
// get drawing context from canvas element
var ctx = canvas.getContext("2d");
if (!canvas || !canvas.getContext) {
window.alert("No canvas or context. Your browser sucks!");
return;
}
var imgd = false;
var width = canvas.width;
var height = canvas.height;
// Try to create image data from scratch
// If that doesn't work, try to load it from the context
// If that fails too, create an array of the same size and pray
if (ctx.createImageData) {
imgd = ctx.createImageData(width, height);
} else if (ctx.getImageData) {
imgd = ctx.getImageData(0, 0, width, height);
} else {
imgd = {
'width': width,
'height': height,
'data': new Array(width * height * 4)
};
}
function animate() {
window.requestAnimationFrame(animate);
// get actual pixel data
var pix = imgd.data;
// run display loop function every 100ms
var i = 0;
for (var y = 0; y < height; y++) {
//do some random stuff with pixel data
var r = Math.random() * 255;
var g = Math.random() * 255;
var b = Math.random() * 255;
var a = 128;
for (var x = 0; x < width; x++, i += 4) {
pix[i] = r;
pix[i + 1] = g;
pix[i + 2] = b;
pix[i + 3] = a;
}
}
// write image data to canvas
ctx.putImageData(imgd, 0, 0);
}
// call animate() for the first time
animate();
When you put this into a HTML file and load it in your browser it should look like this.