JavaScript Animation

Author: Theodore Odeluga

The source files for this project can be downloaded from here

The evolution of animation on the web has been the evolution of the web itself. In barely more than a decade from its inception, the most powerful medium in the world since television went from being a mere collection of static pages to the dynamic entity we know today - partly through animation, both illustrative and interactive.

At one point in this technological revolution, Flash was the influential, if somewhat controversial tool of choice in the world of digital creativity. Since the passing of that platform however (and some time before), the explosion of code based frameworks, libraries and techniques dedicated to the art form has been ubiquitous.

While there are several open source projects and tools available for creating web animation, a few options have proved exceptionally popular among developers over the years as animation online has gone from being a niche interest to an industry in its own right. We'll be looking at a few of them in this article.

In the early days (roughly between 1995 and 2000), website visitors were used to visual effects based on rollover transitions, where a button or other page element would change colour or shape if the mouse cursor hovered over it. At around the same time, banner advertising was also common, where a section of the screen would cycle through a series of images (usually in the GIF format) promoting some product or service.

As online consumers became more sophisticated, the demand for ever more sophisticated techniques to grab their attention also expanded, pushing developers to ever greater feats of innovation. Outside the use of Flash and Java, JavaScript's role in this area was pivotal.

One of the biggest drawbacks with JavaScript animation however (apart from the fact that there weren't really any standards compliant browsers in the 1990's anyway) was that for many years there was no reliable functionality to make web page animation efficient. The developer would have to depend on the hardware's ability to render frames and the consequences of this unreliable hit and miss approach would either result in smooth, consistent movement or jerky, broken jumps between frames.

These limitations were reflected in the use of two old JavaScript functions called setTimeout() and setInterval(). They're still used today, but mostly for event timing in application processes and not so much anymore for animation. Here are some examples.

setTimeout(function(){ alert("Alert!"); }, 3000);

setInterval(function Message(){
let display = document.getElementById("mydiv");
display.innerHTML = "Hi there!";
}, 3000);

setInterval(function(){let remove = document.getElementById("mydiv");
remove.innerHTML = "";
}, 6000);

This was the way it was done for a long time and for years no one had a better solution. Then in 2011 developer Paul Irish created requestAnimationFrame(). This function finally solved the problem of unreliable framerates by shifting the processor intensive burden of rendering from hardware to browser. Even now with the use of GPUs in modern devices and computers, this technique contributes a massive improvement to performance.

If you copy and paste the code below into a text editor, then save it as an HTML page, depending on the age and power of your machine, you should see a difference in performance between the two animation samples.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> requestAnimationFrame vs. setInterval </title>

<style>
#myelement {
background: lime;
width: 100px;
height: 100px;
position:absolute;
}
</style>

<script>

//Un-comment the code for the example you want to run:

//Example 1 - new school
/*function exampleone(time){
var element = document.getElementById("myelement");
element.style.left = (time)/5 + "px";
requestAnimationFrame(exampleone);
}
requestAnimationFrame(exampleone);*/

//Example 2 - old school
var move = 5;
setInterval(function(){var element = document.getElementById("myelement");
element.style.left = move + "px";
move++;
}, 10);

</script>
</head>

<body>
<div id = "myelement"></div>
</body>
</html>

Many of the stunning visual effects we see online today are down to the fundamental change brought about by this single function. However, while JavaScript's own development went from gradual changes to leaps and bounds in the field, another technology from the open web stack was undergoing its own transformation.

CSS (Cascading Style Sheets) has made the web a more beautiful place thanks to its ability to manipulate web page elements and tightly control web page layout.

Designers were happy enough with this and particularly with the convenience of the languages most powerful feature - cascading (as the name suggests) complex styling across a whole site - without the need to edit every single page. Before CSS came along in 1996, this would've been the tedious alternative involving endless copying and pasting (and a significant margin for error).

However, with the major addition of CSS3 came an interesting change; CSS could now encroach on a territory previously owned by JavaScript - web animation.

Later, with the advent of the WebKit engine, first developed for Apple's Safari browser (and later ported to others such as Chrome and Firefox), the use of keyframing was made available in CSS. Keyframing is an old technique dating back to the earliest days of film animation where animators would mark or register certain frames in an animation sequence to indicate a change in the way characters would move.

The new function in CSS was named after this technique and now with "keyframes", its possible to build complex animations in CSS. The example below is pretty simple but it gives an idea of what's possible.

<style>

.box {
width: 100px;
height: 100px;
background-color: #333; }

@keyframes move {
from {
transform: translateX(0);
}

to {
transform: translateX(200px);
}
}

div {
animation-duration: 3s;
animation-name: move;
animation-iteration-count: infinite;
animation-direction: alternate;
}

</style>

In 2005, it was announced that WebKit would be made open source and the benefit of its code was soon brought to other internet browsers. A year later, JavaScript itself underwent further enhancement in the form of a new library that would make it easier to work with DOM elements - jQuery. JQuery essentially empowered programmers who weren't necessarily web designers to do some of the things which were previously the preserve of front-end developers. The library also came with a suite of animation and transition effects. Copy and paste the code below to see an example of this in action.

<!DOCTYPE html>
<html>
<head>
<style>

#graphic {
margin-top: 20%;
height:100px;
width:100px;
background:lime;
position:absolute;
}

#control {
position:absolute;
}

</style>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({left: '500px', top:'-250px'}, 600);
$("div").animate({left:'50px', top:'250px'}, 600);
$("div").animate({left:'600px', top:'-150px'}, 600);
$("div").animate({left: '100px', top:'150px'}, 600);
$("div").animate({left: '10px'}, 600);
});
});

</script>
</head>
<body>

<div id = "graphic"></div>
<button>Animate</button>

</body>
</html>

Despite the technical choices above, the most popular format for animation with JavaScript is HTML5 Canvas. The HTML5 standard was years in the making (almost dating back to the start of the WWW) and it finally received recommendation status from the World Wide Web Consortium (W3C) in October 2014.

One of its principal components is Canvas, a JavaScript based format with an API for manipulating graphics at the pixel level. HTML5 supports a range of additional technologies including local/web storage, audio and video. They're often all used in conjunction with each other - including with Canvas.

The code for the example I've created titled 'Smart enemy animation' is a bit long, so I've not included it in the article but it's part of the project package and you can view it and have fun guiding a character around the screen with your arrow keys, while the enemy of the title follows it around.

Although HTML5 Canvas is the choice most widely used today for browser games and animations, there is yet another format (!!!) that offers an alternative.

Scalable Vector Graphics (SVG) used to be the standard for the Flash MovieClip object. As browsers have now stopped supporting Flash, it's not so easy for me to show you any of my previous work with the technology, but this tutorial on the W3Schools website provides a good introduction to SVG as a standalone open standard (rather than part of Adobe's proprietary software), and so does information on the Wikipedia website.

Similar to the code for the Canvas example, the 3D sample based on Three.js is also quite sizeable so I've again not included it here. Like the HTML5 standard, WebGL's development (leading to spin-off libraries such as Three.js) almost charts the whole history of the web so far, with its origins dating back to experimentation with 3D web applications during the mid-nineties. Given the relative limitations of the time, users had to wait several years before online 3D animation became a realistic possiblity.

WebGL (itself a spin off of OpenGL), finally made it's debut in the 2010's. While powerful, using it involved a steep learning curve. But things didn't stop there. Enterprising developer Ricardo Cabello (AKA Mr.Doob) created Three.js, a library for 3D JavaScript animation which in a similar way to jQuery and its control of DOM elements, abstracted away the finer complexities of working with WebGL. Here are some incredible examples of what's been done with Three.js since. Not long after the creation of Three.js, a competitor, Babylon.js was also released. You can see examples for this library too at its own official site.

Further Development

Fascinating stuff. Animation is one of the things which makes the World Wide Web a continually exciting medium, and something tells me its future will be closely entwined with this other, older form of visual communication. It all depends on how inventive future generations of developers are going to be.

I would recommend specialising in at least one of the above formats. Being able to write code for dynamic graphic behaviour opens up a whole world of possibilities including everything from games and simulations to interactive infographics and advertising. I hope you enjoyed the article and thanks for reading.