Following on from creating a circle with HTML5 and canvas. We’re now going to make the circle move.
You might wonder how you can make it move, using standard elements? Well think back to flash(all those years ago) and how you would rely on frames for movement. It’s the same principal in Javascript. We initialise the “frames” by creating an init function (you can call it what you like) that will call a function every 10 milliseconds and in that function, we would clear the canvas and redraw it further on, creating what seems like movement.
function init(){
return setInterval(update,10);
}
function update(){ ... }
So, an update to the last tutorial. To make it more efficient I’ve had to restructure the Javascript and move it around a bit.
$(function(){ // page load
var c = $("#tut1canvas")[0].getContext('2d'); // this is loading in the canvas element.
var x = 50;
var y = 50;
function init(){
return setInterval(update,10);
}
function update(){
c.clearRect(0,0,500,500);
c.beginPath();
c.fillStyle = '#ccc';
c.arc(x,y,25,0,Math.PI*2,true);
c.fill();
x += 2;
y += 2;
}
init();
});
This should send the ball on a direct diagonal line, see picture below:
So, what happened? Well, we’re using a new function for one.
clearRect(x,y,width,height);
clearRect clears all pixels within the dimensions that you specify. X and Y are the coords from the top left of the canvas and width and height is the width/height, in pixels, of the rectangle in relation to the coords of the canvas. Pretty much the same.
The important bit to the movement is the clearRect and the last 2 lines of the update function.
1. x += 2;
2. y += 2;
What this is doing, is every 10 milliseconds it’s adding 2px to the x and y of the current arc. We are passing the arc x and y as the coords when it’s being drawn, so every time we update it – it gets redrawn 2px on the x and y. If you were to set one of these variables to be a negative value, then the circle would move backwards. The best way to learn is to give it a try, if you break the code then reset it and try again.

