A simple HTML5 animation guide for beginners

HTML5 logo

HTML5 is all the new hype and for a good reason: it is fun, a lot of fun. You can easily visualize things, the backend (Javascript) is already old enough to be reasonably documented, and it is supported by default on many mobile devices and browsers.

There are many, many guides out there already but I figured to write my own and stick to the basics. I’ll assume you already know Javascript or recognize its pseudocode-like syntax. In this guide we’ll make a simple moving circle, I think you’ll find it easy to expand on yourself and I hope it serves as a good start to learn more about this subject. Please don’t hesitate to comment if you have any questions, I’ll gladly answer them.

Getting started

The first thing you’ll need is a simple HTML document with a canvas tag and for the hell of it, let’s make it XHTML valid, thus providing the proper tags:

<!doctype html>
<html>
	<head>
		<title>My first HTML5 animation!</title>
		<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
		<script type="text/javascript" src="first_animation.js"></script>
	</head>
	<body>
		<canvas id="drawing_canvas" width="400" height="400"></canvas>
		<p><a href="http://hexample.com/2012/01/04/simple-html5-animation-guide-beginners/">&lt; Back to the post</a></p>
	</body>
</html>

Alright, now for the things you need to know:

  • HTML5 draws on a tag named <canvas>, it behaves like any other HTML tag so you just give it properties and Javascript will be able to draw on it.
  • The doctype of a HTML5 document is just “html”, as can be seen above. It is good practice to put this on top of all your pages so the browser knows what to render.

Now, what to put in first_animation.js? First things first: you want a handler that’ll be called as soon as your page is fully loaded, so you know when to start your animation. This can be achieved in a number of ways, you have the popular way (and lazy way I often use) of changing the HTML:

<body onload="start_animation()">

But there is also the so-called unobtrusive Javascript which calls for a separation between church and st… er, I mean Javascript code and HTML, where presentation and logic are defined on different layers. So, the cleanest way of handling the onload() event is by putting it in your Javascript file:

window.onload = start_animation;

So, now we’ve got a function that’ll fire as soon as the page is ready, we’ll need to define the canvas object in Javascript so we can actually work with it. First define a global variable in your document, I prefer to call it “ctx” (which is short for context), for obvious reasons. You don’t have to put anything in the actual variable, your start_animation() function will take care of that.

var ctx;

Now you have a variable that’ll represent the object you’ll be drawing with, let’s define it! First, make a new function and use getElementById() to make sure you grab the right variable. I’ve added some comments to explain on the line itself because this could be confusing.

function start_animation()
{
	//First, select the canvas, you'll have to apply a "context" to it later.
	var element = document.getElementById("drawing_canvas");
	//Apply the 2d context, 3d exists too but that's for another day :)
	ctx = element.getContext("2d");
}

At this point you have enabled the magic Javascript needs to draw on the canvas, so let’s draw a circle! Add an extra line to your start_animation():

draw_circle();

And then define a function to actually draw the circle:

function draw_circle()
{
	//Define the colour you want the circle to have, hex (#000064) works too
	ctx.fillStyle= "rgb(0,0,100)";
	ctx.beginPath(); // start a new path
	//arc arguments: arc(x,y,radius,startAngle,endAngle,antiClockwise)
	ctx.arc(200,200,40,0,Math.PI*2,true);
	ctx.closePath(); //close path
	//fill the arc with your specified colour
	ctx.fill();
}

Now, if you run this you’ll have a dark blue circle in the middle of your canvas. Huzzah! Now all you need is a little bit of animation, so let’s change our draw circle function to take X & Y coordinates.

function draw_circle(x,y)
{
	ctx.fillStyle= "rgb(0,0,100)";
	ctx.arc(x,y,40,0,Math.PI*2,true);
	ctx.fill();
}

The next thing you’ll need is something that calls this, and moves the circle. I’ve defined a new global coordinate. For the sake of simplicity, the circle will only move horizontally (X-axis), but obviously it can move in any direction you like.

var circleX = 200;

And made a new function:

function animate()
{
	circleX++;
	draw_circle(circleX, 200);
}

If you run this function once, you’ll have one silly circle that doesn’t move and is at position (201,200), not very interesting at all. We’ll use setInterval() in our original start_animation() function to make sure this function is called at 60 Frames Per Second (FPS).

function start_animation()
{
	var element = document.getElementById("drawing_canvas");
	ctx = element.getContext("2d");
	var interval = setInterval(animate,1000/60);
}

The 1000/60 means “1000 miliseconds / 60″, which on its turn means the code will run at 60 FPS, which is a nice smooth animation, 30 FPS etc. work perfectly fine too, but some perfectionists don’t find it to be smooth enough. If you execute the code you have until now, you’ll see a smooth moving animation of a ball leaving behind a trail. That is because you don’t refresh the frame, and every drawing is added on top of the old one. You’ll have to clear the frame every time animate() is called to fix this, the easiest (and fastest) way to do this is by just drawing a giant square on top of the whole canvas:

function animate()
{
	ctx.fillStyle = "rgb(255,255,255)";
	//Fill a giant rectangle from (0,0) to (400,400) with a white colour
	ctx.fillRect (0, 0,  400, 400);
	circleX++;
	draw_circle(circleX, 200);
}

If you know a bit about Javascript I think this is a good enough start for basic HTML5 drawing, there are many more things you can draw with, fillRect and arc are just two of a very long list. The drawing shapes tutorial from Mozilla is a very good reference.

I’ve included my complete code + a way to keep the ball from leaving the screen. You can also view a live example here.

var ctx;
var circleX = 0;
var direction = 1;
window.onload = start_animation; 

function start_animation()
{
	var element = document.getElementById(&quot;drawing_canvas&quot;);
	ctx = element.getContext(&quot;2d&quot;);
	var interval = setInterval(animate,1000/60);
}
function animate()
{
	circleX += direction;
	if(circleX &lt; 0)
	{
		direction = 1;
	}
	else if(circleX &gt; 400)
	{
		direction = -1;
	}
	ctx.fillStyle = &quot;rgb(255,255,255)&quot;;
	ctx.fillRect (0, 0,  400, 400);
	draw_circle(circleX, 200);
}

function draw_circle(x,y)
{
	ctx.fillStyle= &quot;rgb(0,0,100)&quot;;
	ctx.beginPath();
	ctx.arc(x,y,40,0,Math.PI*2,true);
	ctx.closePath();
	ctx.fill();
}

Please note this isn’t even close to being Object-oriented Javascript, nor is it intended to, as it would hinder readability for new Javascript coders quite a bit. Depending on feedback I’ll get on this, I might make more tutorials in this style, so please share your thoughts or questions in the comments!

Tags: , ,

3 Responses to A simple HTML5 animation guide for beginners

  1. Kapila

    Should there be a ctx.stroke() command somewhere? Without it in firefox, nothing happens.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>