A little canvas experiment

Here's some basecode for simple canvas animations:
<html>
<head>
<script type="text/javascript">
onload = function() {
  //get canvas element
  var canvas = document.getElementById('canvasexperiment');
  //get drawing context from canvas element
  var ctx = canvas.getContext("2d");

  if (!canvas || !canvas.getContext) {
    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)};
  }
  //get actual pixel data
  var pix = imgd.data;

  //run display loop function every 100ms
  setInterval(function() {
    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);
  }, 100);
}
</script>
</head>
<body>
<canvas id="canvasexperiment" width="128" height="512"></canvas>
</body>
</html>
When you put this into a HTML file and load it in your browser it should look like this:

Edit: Also note this shim for smooth animation.

Comments