Close

Basics of HTML5 animation

Animation in a HTML page can serve many different purposes, and can be achieved using many different techniques. Perhaps you want to fade a UI element, create an infographic, or build a game using simple animation.

In this post I will highlight the absolute basics for HTML animation:

  • DOM animation
  • Canvas animation
  • SVG animation

In a followup post I will highlight a number of engines and frameworks for each kind of animation.

DOM animation

DOM (Document Object Model) animation is what you see most in regular webpages. A webpage consists of DOM elements that you can access with javascript or CSS. You can simply change properties of DOM elements to achieve animation.

HTML PAGE



  
a simple box

Now we will change the CSS properties of this box over time – creating an animation effect – using javascript:

JAVASCRIPT

var b = document.getElementById("box");
var w = 100;
setInterval(function(){
   w++;
   b.style.width = w + "px";
}, 200)

What happens here is that javascript updates the ‘width’ css property of the box element every 200 milliseconds.

This works, although simple effects like this are more easily achieved using CSS only:

CSS

#box{
    width:100px;
    transition:width 2s;
}
#box:hover{
   width:200px;
}

CSS transitions define how the state of a DOM element will animate if you change its CSS properties. This example will animate the width of the box as you hover the mouse over it. Note that this transition effect is defined in the base setting of the box, but the effect only applies when the CSS values actually change.

Canvas animation

A canvas is a single DOM element on your webpage. You can compare a canvas with a single PNG or JPG image. When animating a canvas, you are actually addressing individual pixels on this canvas sheet. This is both more complex, and more limited than directly animating DOM elements, so why would you want to use canvas animation?

– Canvas animation is fast. Manipulating individual pixels is what the GPU in your computer was made for. This is many times faster than moving DOM elements around a HTML page.
– For this reason, a canvas lends itself well to complex animation such as particle effects, filtering images, 3D rendering, and animating hundreds of spaceships and enemies in a game.

A simple example of an animating circle using canvas animation: (example from Kirupa)

HTML

JAVASCRIPT

var mainCanvas = document.getElementById("myCanvas");
var mainContext = mainCanvas.getContext('2d');
 
var canvasWidth = mainCanvas.width;
var canvasHeight = mainCanvas.height;
 
var angle = 0;
 
var requestAnimationFrame = window.requestAnimationFrame || 
                            window.mozRequestAnimationFrame || 
                            window.webkitRequestAnimationFrame || 
                            window.msRequestAnimationFrame;
 
function drawCircle() {
    mainContext.clearRect(0, 0, canvasWidth, canvasHeight);
     
    // color in the background
    mainContext.fillStyle = "#EEEEEE";
    mainContext.fillRect(0, 0, canvasWidth, canvasHeight);
     
    // draw the circle
    mainContext.beginPath();
     
    var radius = 25 + 150 * Math.abs(Math.cos(angle));
    mainContext.arc(225, 225, radius, 0, Math.PI * 2, false);
    mainContext.closePath();
     
    // color in the circle
    mainContext.fillStyle = "#006699";
    mainContext.fill();
      
    angle += Math.PI / 64;
     
    requestAnimationFrame(drawCircle);
}
drawCircle();

JSFiddle

Canvas animation is primarily used for games, where a lot of interaction happens inside a fixed area which does not have to be responsive.

SVG animation

SVG has been around on the web for a long time. SVG uses vectors to draw images instead of pixels. An SVG image is actually just a block of code, describing where and how to draw lines and shapes. This has several big advantages:

– Images can scale without deteriorating in quality. This is great for responsive websites.
– Individual parts of an SVG can be interactive.
– Since the image is actually code, you can generate an SVG based on data – this is great for infographics.
– And since all elements of an SVG drawing are still individually addressable, you can animate parts or everything in an SVG.

SVG animation can be achieved through CSS (by setting CSS values of individual SVG elements) or by SVG’s native animation language.

HTML


  

CSS

svg { width: 300px; height:300px; }
polygon { 
    fill: #FCCCCF; 
    stroke:#ED1C24; 
    stroke-width: 5; 
    transition:fill 2s;
}
polygon:hover {fill:#FF00CC; }

This CSS animates the color of the polygon fill when you hover over it.

JSFiddle

A note on using RequestAnimationFrame

‘RequestAnimationFrame’ is a Javascript function that handles animation frames for you. The browser makes sure it doesn’t run when the tab containing your animation isn’t visible, and that your animation doesn’t crash the browser.
Of course every browser implements this slighty differently, therefore it’s handy to include requestanimationframe.js, which will make sure your animation runs in every browser.

Javascript code example: this resizes a box using requestAnimationFrame:

var b1;
var w=10, h=10;
				
function init() {
	b1 = document.getElementById("box1");
	animateBox();
}
		
function animateBox(){
	w ++;
	h ++;
	// use w and h variables to resize the box via CSS
	b1.style.width = w + "px";
	b1.style.height = w + "px";
	
	// keep going as long as the box is smaller than 500 pixels
	if (Math.abs(w) < 500){
		requestAnimationFrame(animateBox);
	}
}

A note on DOM animation using jQuery

jQuery has an animation function, and automatically gives each page element an animation queue, so that you can create timeline-based animations.

Note that animating large amounts of elements with jQuery tends to be rather slow. This can be partially solved by not animating CSS position values, but instead animating CSS transform values of an element. If you want to use a lot of animation, it's better to rely on pure CSS or use a dedicated animation library.

Code example: a simple jQuery animation:

$('#box').animate({left:'250',top:'250'}, 2000);

Example: these two animation functions are automatically queued after another:

$("#box")
	.animate({top: "250"}, {duration: 2000})
	.animate({left: "250"}, {duration: 2000});

You can also manually create a queue, this enables you to put in extra code that gets executed in sequence:

$("#box")
	.queue(function(next) {
	    $(this).animate({opacity: 0.6}, 
	    {duration: 2000, queue: true});
	    next();
	})
	.queue(function(next) {
	    $(this).animate({top: "220"},
	    {duration: 1000})
	    next();	
	});	

Read all about jQuery animation.