Continuing my research and development into HTML5 Canvas. Having previously tried to create a HTML5 Canvas animation, and failing, I set myself the task of trying again. This time with the aid of Rob Hawkes' 'Foundation HTML5 Canvas For Games and Entertainment'.
The basis of animating in HTML5 Canvas is a simple 3 step looped process; updating everything that needs to be drawn (e.g. moving the position of your elements), clearing the canvas and then redrawing using your updated variables/positions.
A simple animation would be to move a box along a single line:
$(function() {
var canvas = $("#canvasElement");
var context = canvas.get(0).getContext("2d");
var canvasWidth = canvas.width();
var canvasHeight = canvas.height();
var x = 10;
var y = 10;
function moveBox() {
// Clears out our canvas to redraw
context.clearRect(0,0, canvasWidth, canvasHeight);
// Draws our box
context.fillRect(x, y, 10, 10);
// Increases our x variable by 1 each time this function is called, moving our box along the horizontal axis
x++;
// Calls our moveBox() every 33 milliseconds, causing the whole process to loop
setTimeout(moveBox, 33);
}
// Call the function once to call to start things off
moveBox();
});
Hopefully the comments in the code above explains what is happening within each step of our process. And that's it! You can view the demo here.
Having achieved a simple animation, I wanted to take things further, and using more guidance from my bible that is Rob Hawkes' book, I was able to create circles animating around another circle - the basis of something we want to work on and develop further for the Creative Jar website. You can view the demo and source code here.