The focus for week 4 of the W3C HTML5 course was animation. We’ve been displaying a lot, but it’s been fairly static up to this point. This week, we learned about events, interacting via the keyboard and mouse, and the three steps of animation:

  1. Clear the canvas
  2. Draw the items on the canvas
  3. Move the items (won’t take effect until the loop iterates, and you clear the screen and draw again)

It sounds simple once you know it, but only in hindsight. I knew we were going to learn about animation, but wasn’t sure how exactly it was implemented. I figured each shape on the canvas was drawn one at a time, but instead we’ve been clearing the entire canvas, recalculating positions, and then redrawing them again at their new locations.

These 3 steps loop fairly quickly, about 60 times per second (equivalent to 60 fps), when using HTML5’s new requestAnimationFrame() function.

Graph (take 2)

First, here’s my graph again, but this time the bars “fill up” smoothly. Click the button below the graph to see the animation again.

Full source at JS Bin.

Graph (take 2.2)

Here's the graph yet again, but now you can interact with it.

Click on a bar and drag up and down to change the value.

Full source at JS Bin.

Bouncing Ball

Finally, a simple bouncing ball. It changes color when it hits a wall and reverses its course.

Click on the ball to speed it up. Press the "Reset" button to slow it down again.

Full source at JS Bin.