Javascript Animation Introduction

The code for this tutorial can be found here.


To create the illusion of animation we need to swap out concurrent images every 40ms (to achieve 25 frames per second, FPS). We can do this by using a call to the Javascript function setInterval() and then use the function, which is called every 40ms, to draw onto an HTML5 Canvas element.

Creating the Canvas Element

We can create a canvas element using the following snippet
<div id='canvas_div'>
<canvas id="canvas" width="600" height="250">
<p>Your browser does not support the canvas element.</p>

Getting the drawing context

First we need to add a call to a Javascript function we will create, called once the page has finished loading - we do this by adding an appropriate attribute to the <body> tag.
<body onload='page_loaded()'>
And then in Javascript we create the function that will be called (the names must match)
var canvas = null;
var ctx = null;

function page_loaded(){
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');;
If we try to grab references to the elements before the page has finished loading then the elements won't exist and it will fail.

Animation Loop

To get the animation working we need to create the loop. We do that by creating a function (called update() - although it can be called anything).
function update(){
// Update and draw our animation
And we need to call setInterval inside the page_loaded() function.
setInterval(update, 40); // 40 is the number of ms between calls

Drawing the cirlce

We need to draw the on every update call and we can do that with the following code
ctx.clearRect(0, 0, canvas.width, canvas.height);;

// Draw the circle
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
// Complete the drawing of this set of lines
First thing is the clear the canvas - using ctx.clearRect() to make sure the old circle isn't still there when we draw it in it's new position. Then followed by ctx.beginPath() to let the context know that we are about to draw some coordinates. Next up is the call to draw the actual circle - using the ctx.arc() function. Passing in the X location, Y location, radius, start angle and end angle, in that order. By going from 0 - 2π (measured in radians) it means we draw a complete circle. Explanations of this can be found through Google or in other tutorials.

Moving the Circle

We now need to create a variable to hold the location and move it up and down over time. We do that by changing to the update function to look like this.
var loc = 50;
var isMovingLeft = false;

function update(){
// Move the ball
loc -= 4;
loc += 4;
if(loc > 200){
isMovingLeft = true;
}else if(loc < 50){
isMovingLeft = false;

// Do the drawing
ctx.clearRect(0, 0, canvas.width, canvas.height);;

// Begin to draw lines
// Draw the circle
ctx.arc(loc, 75, 50, 0, 2 * Math.PI);
// Complete the drawing of this set of lines
When loading the page you should see a circle moving in from right to left and back again.