Rick's Tech Talk

All Tech Talk, Most of the Time

Diving into HTML5

Like a lot of programmers, I've begun to wonder what all the fuss is about regarding HTML5. Casting about, I found Mark Pilgrim's fantastic tutorial on HTML5, appropriately titled "Dive into HTML5". I've been mucking with the canvas element, testing out the basics, and I put together a small web page showing a very simple random but colorful "box" generator.

canvasdraw.PNG

There's nothing particularly "interesting" about the drawing code, other than the simple fact that there's a drawable object directly in HTML. I have heard of SVG (scalable vector graphics), but that never caught my fancy. SVG is ultimately vector-based, versus the pixel-level control offered by the canvas. That kind of drawing reminds me of the stuff I did for Tetris.

For my box generator, the bulk of the code is in this one JavaScript function:

  1. var d_canvas = document.getElementById("d");
  2. var d_context = d_canvas.getContext("2d");
  3. // Draw 10 boxes at a time
  4. function draw_boxes() {
  5.   var counter = 0;
  6.   while (counter < 10) {
  7.     d_context.fillStyle = randomColor();
  8.     d_context.fillRect(
  9.       get_random(d_canvas.width),  // x
  10.       get_random(d_canvas.height), // y
  11.       get_random(30),              // width
  12.       get_random(40));             // height
  13.     counter++;
  14.   }
  15. }

But visit my first HTML5 canvas demo page yourself, and view the source. There's a lot that can be done with the new canvas tag. I think it's cool that I can do some basic 2D graphics in nothing more than my browser and JavaScript!