HTML5 animation tutorial

We are going to animate a moving car with two different HTML5 techniques.


HTML5 is becoming more and more popular. With the increasing popularity of mobile devices such as tables and smartphones, the need for alternatives to the popular Flash plugin from Adobe has also been grown. Just recently, Adobe announced that Flash will no longer be supported for mobile devices. This means that Adobe itself will focus on HTML5 as a key technology for those devices – and desktop systems sooner or later.

One disadvantage of HTML was the lack of multimedia techniques. In HTML, you could not display a video or draw on the screen. With HTML5, new elements such as <video> and <canvas> have been introduced. Those elements give developers the possibility to use multimedia technology in “native” HTML, just by writing some JavaScript in combination with HTML. A basic action that should be provided by multimedia technologies is animation. In HTML5, there are some ways to create such actions.

In this article, I will only compare the new <canvas> element with the upcoming CSS3 animation technique. Other possibilities would include the creation and animation of DOM elements or SVG elements. Those possibilities will not be included in this discussion. It should be noted from the beginning that the canvas-technology is supported in the current releases of all major browsers, while CSS3 animations are only possible in the latest editions of Firefox and Chrome. The next IE will also provide CSS3 animations.


I am currently giving a lecture on creating WebApplications using HTML5, CSS3 and JavaScript. This is a lecture with tutorials. For one of the tutorials, I picked a sample canvas animation – just showing in which direction we are heading to with a technology like this. Then I introduced the CSS3 animation in the lecture (everyone was very excited about it) and wanted to create a simple homework task using the CSS3 animations. What came to my mind was: how easy or hard would it be to actually transform the canvas animation into a complete CSS3 animation?

This involved several parts:

  • Creating all the different <div>-elements in order to “box” everything
  • Draw everything using styles on those elements with style rules like borders, background-gradients and rounded corners
  • Actually animating the elements

The reason for using CSS3 animation over the <canvas>-element is quite important: While browsers can optimize their elements performance (regarding their style, i.e., CSS), they cannot optimize our custom drawing routines used in a canvas. The reason for this lies in the browser’s ability to use hardware mainly the graphics card. Currently the browser does not give us direct access to the graphics card, i.e., every drawing operation has to go over some function in the browser first.

This problem could be prevented with techniques such as webgl, where the browser does give the developer direct access to the graphics card. However, this is treated as a security problem and will not become standardized. One important rule for developing WebApplications is standardization – since this is our portal to a huge customer base. If we excluded some of the most popular browsers, we would certainly lose a lot of potential visitors.

Starting with Canvas

Our basic HTML document looks like the following:

 Collapse | Copy Code
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8"/>
<title>Animations in HTML5 using the canvas element</title>
<canvas id="canvas" width="1000" height="600">Your browser does not support the 
<code>&lt;canvas&gt;</code>-element. Please think about updating your browser!</canvas>
<div id="controls">
<button type="button" onclick="speed(-0.1);">Slower</button>
<button type="button" onclick="play(this);">Play</button>
<button type="button" onclick="speed(+0.1);">Faster</button>

Here we set the HTML5-Doctype and build a page containing a <canvas> for drawing the animation and some buttons contained in a panel (<div>). We could have shortened the document by omitting certain tags. One of the advantages of HTML5 is that each browser has to implement certain fallbacks, e.g., if a tag is not closed or if a certain tag is missing. The shown (more complete and verbose) form is my personal favorite.

A canvas alone would not make a great painting – nor does it give us some animation. What does the actual drawing? It’s some JavaScript! The required <script>-tag is already placed in the <head>-section. In this case, we will not use external JavaScript files to get the required lines of code. This makes only sense if you consider using not many lines of code (small size) and non-repeating JavaScript. Otherwise you could benefit from the browser’s caching as well as multiple (download) connections. Another important point by using external JavaScript files is to consider moving the script-tags to the bottom of the document in order to prevent performance problems.

Let’s start by declaring some variables:

 Collapse | Copy Code
var	dx = 5,				// Velocity at rate 1
	rate = 1, 			// The current playback rate
	ani,				// The current animation loop
	c,				// (Drawing) Canvas Context
	w,				// (Car, hidden) Canvas Context
	grassHeight = 130,	// Height of the background
	carAlpha = 0,		// Rotation-angle of the tires
	carX = -400,		// (x-)Position of the car (will move)
	carY = 300, 		// (y-)Position of the car (will stay constant)
	carWidth = 400, 	// Width of the car
	carHeight = 130,	// Height of the car
	tiresDelta = 15,	// Distance from one tire to the closest edge of the chassis 
			// of the car
	axisDelta = 20,	// Distance from the bottom of the chassis of the car 
			// to the axis with the tires being attached
	radius = 60;	// Radius of one tire

	// In order to init the car canvas (hidden) we use this anonymous function
(function() {
	var car = document.createElement('canvas');	// Creating the element
	car.height = carHeight + axisDelta + radius;	// Setting the appropriate 
						// attributes
	car.width = carWidth;
	w = car.getContext('2d');			// Now we can set the car canvas
})(); // Executed directly

As you can see, most of the variables are actually used as constants. This means the code will give you some freedom in order to adjust the dimensions of the car as well as some other parameters like the speed of the car. The change in the rotation of the tire can actually be calculated by using the ratio of dx to the radius.

Another interesting property arises by looking at the bottom of the code. Here I use an anonymous function. This can be very useful in some cases. This means that variables that are declared within the scope of the anonymous function like car will be deleted by the browser and most importantly will not cause any conflicts with other existing variables.

Why is there a second (invisible) canvas set up? First of all, this will be useful in the transition to CSS3. However, this approach is also very useful in general. By using a canvas for each major object we are animating, we will be able to keep their states as they are, i.e., if we do not have to redraw them we do not have to as supposed to the approach where we will wipe does drawings away with a clean of the main canvas. Another reason is that this model allows us to think more physical. We do not have to animate the chassis (moving) and the tires (moving and rotating) separately, but just as a whole thing meaning the tires (rotating) within the car (moving). This states the physical model more closely, where the tires are rotating which makes the car moving.

Starting the loop:

 Collapse | Copy Code
function play(s) {				// The referenced function, s is the button
	if(ani) {				// If ani is not NULL we have an animation
		clearInterval(ani);	// So we clear (stop) the animation
		ani = null;		// Explicitly setting the variable to NULL
		s.innerHTML = 'Play';	// Renaming the button
	} else  {
		ani = setInterval(drawCanvas, 40);	// We are starting the animation 
						// with 25 fps
		s.innerHTML = 'Pause';	// Renaming the button

This function has already been referenced by the HTML we’ve written. Here we just start or stop the animation depending on the current state that is displayed using the ani variable. The framerate has a maximum of 25 frames per second – this might not be the best choice. jQuery is using 77 fps (13 ms) as a default for its DOM object animation. In case of this simple animation, it should give a good insight. An important issue is that our logic (dx = 5) will be bound to those 25 fps. This is something to be careful about when building professional animations or even games.

Let’s have a look at the main drawing function that will be called in the loop:

 Collapse | Copy Code
function drawCanvas() {
	c.clearRect(0, 0, c.canvas.width, c.canvas.height);	// Clear the (displayed) 
							// canvas to avoid errors;		// Saves the current state of properties (coordinates!)
	drawGrass();		// Draws the background (grass)
	c.translate(carX, 0);	// Does some coordinate transformation
	drawCar();		// Draws the car (redraws hidden canvas)
	c.drawImage(w.canvas, 0, carY);	// Draws the car actually to visible canvas
	c.restore();	// Restores to last saved state (original coordinates!)
	carX += dx;		// Increases the position by the dx we set per time
	carAlpha += dx / radius;	// Increases the angle of the tires by the ratio

	if(carX > c.canvas.width)	// We keep some periodic boundary conditions
		carX = -carWidth - 10;	// We could also reverse the speed dx *= -1;

Basically we just redraw the image. The animation is actually coming from two little methods inside. First we use a translation of coordinates to always draw to the same coordinates but being placed on a different location. The second one is the incrementation of the car’s current position. Without one of those two calls, the car would not move at all! We also outsourced as much code as possible, making it more maintainable (unfortunately, this can also decrease JavaScript code performance).

Why are coordinate transformations so important? The offer us some nice possibilities: Rotating something without writing any mathematical function at all! Or as we have seen: We can just draw to the same coordinates but receive different results. This is the power of coordinate transformation. The translation method is called by using context.translate(dx, dy) and allows us to set a new center (0, 0). The usual center is the upper left corner. If we would rotate without translating at all, we would always just rotate around the upper left corner. In order to rotate around the center of a canvas, we could use something like:

 Collapse | Copy Code
context.translate(context.canvas.width / 2, context.canvas.height / 2)

Now we look at the function for drawing the car itself:

 Collapse | Copy Code
function drawCar() {
	w.clearRect(0, 0, w.canvas.width, w.canvas.height);	// Now we have to 
							// clear the hidden canvas
	w.strokeStyle = '#FF6600'; 		// We set the color for the border
	w.lineWidth = 2;			// And the width of the border (in pixels)
	w.fillStyle = '#FF9900';		// We also do set the color of the background
	w.beginPath(); 			// Now we begin some drawing
	w.rect(0, 0, carWidth, carHeight);	// By sketching a rectangle
	w.stroke();			// This should be drawn (border!)
	w.fill();				// And filled (background!)
	w.closePath();			// Now the close the drawing
	drawTire(tiresDelta + radius, carHeight + axisDelta);		// And we draw 
								// tire #1
	drawTire(carWidth - tiresDelta - radius, carHeight + axisDelta);// Same routine, 
							// different coordinates

Here we used some of the possibilities that the <canvas>-element offers us. On the hand we do use paths (very simple – and in this case more or less obsolete since we could have used the drawRect() and fillRect() method. Again we outsourced some code in order to obtain a better maintainability. In this case, this is totally justified since we just have one method to take care of (drawTire()) instead of two identical code blocks that form one big mess.

Finally, let’s have a look at the method for drawing one of the tires:

 Collapse | Copy Code
function drawTire(x, y) {;				// Again we save the state
	w.translate(x, y); 		// And we perform a translation 
					// (middle of the tire should be centered)
	w.rotate(carAlpha);		// Now we rotate (around that center)
	w.strokeStyle = '#3300FF'; 		// Setting the draw color
	w.lineWidth = 1;			// The width of the border (drawline)
	w.fillStyle = '#0099FF';		// The filling / background
	w.beginPath();				// Another sketching is started
	w.arc(0, 0, radius, 0, 2 * Math.PI, false); 	// With a full circle around 
					// the center
	w.fill(); 			// We fill this one
	w.closePath(); 			// And close the figure
	w.beginPath();			// Start a new one
	w.moveTo(radius, 0);		// Where we move to the left center
	w.lineTo(-radius, 0); 		// Sketch a line to the right center
	w.stroke();			// Draw the line
	w.closePath();			// Close the path
	w.beginPath();			// Start another path
	w.moveTo(0, radius);		// Move to the top center
	w.lineTo(0, -radius); 		// And sketch a line to the bottom center
	w.stroke();			// Draw the line
	w.closePath();			// Close it
	w.restore();			// And restoring the initial state 
					// (coordinates, ...)

Additionally, I’ve added a preview image by using the onload-event of the <body>-element. I also included a method to increase the speed of the animation by changing the value of the dx variable. The framerate will not be changed in order to increase or decrease the speed.

This is the result of our coding. A car moving around in a canvas!

This example can be viewed live at

Moving to CSS3

The basic HTML document now has the following format:

 Collapse | Copy Code
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8"/>
<title>Animations in HTML5 using CSS3 animations</title>
<div id="container">
<div id="car">
<div id="chassis"></div>
<div id="backtire" class="tire"><div class="hr"></div><div class="vr"></div></div>
<div id="fronttire" class="tire"><div class="hr"></div><div class="vr"></div></div>
<div id="grass"></div>

The document looks quite similar to the one before. However, some things can be noted right away:

  • There is no <script>-element prepared. Instead, we will use a <style>-declaration.
  • There are no controls for setting the speed or play and pause. This is actually one of the key differences I will explain later (interaction).
  • The whole scene is already presented in HTML-elements. They are not styled right now, but they do represent the scenario we want to animate.

While animating something in a canvas is mostly a programming job, we clearly shifted towards a design problem here. We can only manage to animate the scene appropriately if we build a correct model of the scene using HTML-elements (well, <div>s). In this logical scenario, the <div id="container"> represents the canvas from before, <div id="car"> is the HTML-element that is equivalent to the hidden canvas of the previous example and <div id="grass"></div> is exactly the element that has been drawn using drawGrass() before.

The basic CSS outline is the following:

 Collapse | Copy Code
	position: relative;	/* Relative pos. - just that we can place 
				absolute divs in there */
	width: 100%;		/* Yes this will get the whole page width */
	height: 600px;		/* and 600px height */
	overflow: hidden;	/* Really important */

	position: absolute;	/* We position the car absolute in the container */
	width: 400px;		/* The total width */
	height: 210px;		/* The total height incl. tires and chassis */
	z-index: 1;		/* car is in front of the grass */
	top: 300px;		/* distance from the top (y-coordinate) */
	left: 50px;		/* distance to the left (x-coordinate) */

	position: absolute;	/* This defines the space of our car w/o tires */
	width: 400px;		/* The total width */
	height: 130px;		/* The height of the chassis */
	background: #FF9900;	/* Some color */
	border: 2px solid #FF6600;	/* Some thick border */

	z-index: 1;		/* Always in front of the chassis */
	position: absolute;	/* Absolute positioned */
	bottom: 0;		/* Will be placed at the bottom of the car */
	border-radius: 60px;	/* And there is our radius ! */
	height: 120px;		/* 2 * radius = height */
	width: 120px;		/* 2 * radius = width */
	background: #0099FF;	/* The filling color */
	border: 1px solid #3300FF;	/* And the border color and width */

	right: 20px; /* Positions the right tire with some distance to the edge */

	left: 20px; /* Positions the left tire with some distance to the edge */

	position: absolute;	/* Grass is absolute positioned in the container */
	width: 100%;		/* Takes all the width */
	height: 130px;		/* And some height */
	bottom: 0;		/* 0 distance to the bottom */
	background: -webkit-linear-gradient(bottom, #33CC00, #66FF22);
	background: -moz-linear-gradient(bottom, #33CC00, #66FF22);
	background: -ms-linear-gradient(bottom, #33CC00, #66FF22);
	background: linear-gradient(bottom, #33CC00, #66FF22); /* Currently we need 
							all of them */

.hr, .vr	/* Rules for both: hr and vr */
	position: absolute;	/* Want to position them absolutely */
	background: #3300FF;	/* The border color */

	height: 1px;		/* Linewidth of 1 Pixel */
	width: 100%;		/* Just a straight line (horizontal) */
	left: 0;
	top: 60px;		/* Remember 60px was the radius ! */

	width: 1px;		/* Linewidth of 1 Pixel */
	height: 100%;		/* Just a straight line (vertical) */
	left: 60px;		/* Remember 60px was the radius ! */
	top: 0;

Here we use classes and IDs to attach rules one or multiple times. This can be seen best by looking at the code for creating a tire. We do use two different IDs (fronttire and backtire) for distinguishing between different positions. Since both share the rest of their properties (and a rotation!), it was just useful to give them also a class (tire) which attaches some CSS rules to the corresponding elements.

The horizontal and vertical lines will be drawn using the classes hr and vr. We can use the position: absolute; andposition: relative; rules to set positions for each child-element within the mother-element. For the grass, we required a gradient to be drawn. This is no problem in CSS3. Well, maybe it is a small problem since the browser vendors are currently using vendor specific prefixes for those rules. This is an annoying fact and will hopefully vanish within the next year.

A really important rule can be found in the container itself. By setting overflow: hidden; we prevent the car from escaping from our beautiful container-world. This means that the car will behave the same way as in the previous scenario, where it was not possible to draw outside the canvas-area. However, one more really important thing is missing: the animations itself!

Definitions of the keyframes:

 Collapse | Copy Code
@keyframes carAnimation
	0% { left: -400px; }	/* Initial position */
	100% { left: 1600px; }	/* Final position */

@keyframes tyreAnimation
	0% { transform: rotate(0); }	 	/* Initial angle */
	100% { transform: rotate(1800deg); }		/* Final angle */

The first comment on those lines is a really important one: do not try making this at home! I do not show the real code here for a purpose. This is how it should look like. However, it does not (but it looks similar). The problem is that CSS3 keyframes are quite new and therefore (yes, you guess (or know) it) you require those prefixes again. Also CSS3 transforms do require prefixes. So just copy those lines and add -webkit- and -moz- and others (IE is about to come to the CSS3 animations party with version 10, hopefully Opera is about to follow!) in front of keyframes and transform.

The next thing you’ll notice is that the syntax is really clean and smooth. You just specify some keyframes (in this case, just one as an initial frame and one as a final frame) and the browser will calculate the rest. However, we cannot integrate such nice physical considerations like the relation between the angle and the position from the previous example.

Now that we specified some keyframes we need to integrate them! How does that look:

 Collapse | Copy Code
	animation-name: carAnimation;
	animation-duration: 10s;
	animation-iteration-count: infinite;
	animation-timing-function: linear;

	animation-name: tyreAnimation;
	animation-duration: 10s;
	animation-iteration-count: infinite;
	animation-timing-function: linear;

Again – be cautious when trying this at home. You will need some copy and paste plus you’ll have to add the appropriate prefixes in front of those entries. So this tells the browser which set of keyframes to take for the element and what kind of frame distribution within which time to consider. We also tell the browser the number of repetitions to perform. In this case, we will end up with an infinite loop.

This is the result of our styling. A car moving around in a div!

This example can be viewed live at

Comparison of the Two Methods

In my opinion, both of those methods have their benefits. The first one is actually pretty straight forward from a programmer’s perspective (however, it took quite long until this was possible in HTML / JavaScript). The second one does offer some really nice features and will most certainly be used in an amazing way to build websites that will certainly have an impact on the web’s future.

Pro Canvas-Animations

  • Interaction (like pause, slower, faster, …) is easily possible.
  • We can connect values to form one physical unit directly.
  • We do not need to know or have a complete structure before the animation.

Pro CSS3-Animations

  • The performance is definitely better.
  • We can use the full screen (100% does not work with the canvas element).
  • The frames are computed by the browser – we just specify the keyframes.

All in all, it will depend on the project (as usual). Even though I thought about some possible workarounds to actually stop an infinite CSS3-animation (and start again), it would be tedious to actually implement this in a bigger multimedia animation. Here the interaction possibilities are a clear indicator for a canvas-animation. On the other side, some small (non-interactive) animations could be done by the CSS3 technique. It provides a nice clear syntax that can be GPU accelerated by modern browsers and can be styled to fit everywhere.

Points of Interest

While writing a lot of <canvas>-animations, I never had to opportunity to write an actual CSS3 animation. This was certainly related to the propagation of this really new technique. Now that Firefox implemented the keyframes and with Microsoft up to come we will most certainly see more keyframe rules online. I thought that this technique was quite hard to write and got really surprised how easy it is. I actually had more problems with the linear gradient syntax than the keyframes one.

My only hope is that browser vendors will stop rolling out CSS rules with those prefixes. In nightly builds or such they are acceptable, but having something in a final build that is either not the standard (why rolling it out?) or standardized (why prefixing it?) but with a prefix is just a mess for web developers.

About hackmyass
free the internet

2 Responses to HTML5 animation tutorial

  1. Can I review this tutorial in to Indonesian language at my blog? thanks..

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: