HTML5: requestAnimationFrame made easy

I’ve been searching for a recent, clear article on how to start using requestAnimationFrame and it just doesn’t seem to exist.

requestAnimationFrame is an API for animating styling changes, canvas or WebGL. It removes the need to use a setInterval or setTimeout to continuously call an animation function and, along with it, optimises the animation both in visual and resource performance.

This sounds great, but the API is still experimental and so is liable to change, which it has done over the past year. This means a lot of the demos of the API online are outdated. Those that aren’t, make the API seem much harder to use than it actually is. This is what I’m hoping to remedy.

Example

To start with, you need a basic HTML5 page with a canvas on it.

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>My Animation</title>
        <style type="text/css" media="all">
            /* CSS */
        </style>
        <script type="text/javascript">
            //Javascript
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="960" height="500">
        </canvas>
    </body>
</html>

Simple. Now lets get into the Javascript.

First we’ve got a bit of set up to do.

window.onload = function(){
    // Get a reference to the canvas to work on.
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");

    // Collect all the browser prefixed versions into one variable
    window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;

    // Get the current time
    var date = new Date();
    var time = date.getTime();

    // Create global variables to store the x and y positions of the shape we're going to animate.
    rectXPosition = 0;
    rectYPosition = 0;    

    // Call the animation function for the first time.
    animate(time);
}

Now let’s look at the animate function.

function animate(lastTime){
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");

    // Get the current time (The value we created in setup will not update)
    var date = new Date();
    var time = date.getTime();

    // Get the difference between the time last animated (or on setup) and now
    var timeDiff = time - lastTime;

    // Set the speed of the animation in pixels per second
    var linearSpeed = 100;

    // Calculate how far the shape will travel in the time difference found previously
    var linearDistEachFrame = linearSpeed * timeDiff / 1000;

    // Update the position of the shape based on the calculated distance
    rectXPosition = rectXPosition + linearDistEachFrame;

    // Copy the current time to the lastTime variable (ready to fire the next animate call)
    lastTime = time;
    //**Now begin drawing on the canvas**
    // Clear the shape
    context.clearRect(0, 0, canvas.width, canvas.height);
    // Draw the shape in it's new position
    context.fillRect(rectXPosition,rectYPosition,100,100);
    // Check to see if the square is at the edge
    if (rectXPosition > 400) {
        // Request a new frame and call this function again
        requestAnimationFrame(function(){
            animate(lastTime);
        });
    }}

That’s it!

Try a DEMO

Anything more?

Because the API is still not quite all there, people have worked on a simple shim for the basic functionality shown here. To implement this, replace the code…

window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;

…with this…

window.requestAnimationFrame = (function(callback){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback){ window.setTimeout(callback, 1000 / 60); };})();

Read further

Mozilla Developer Network page for requestAnimationFrame
W3C entry for requestAnimationFrame
HTML5 Canvas Tutorial on Canvas Animation

Advertisements

Published by

Andrew Bridge

A student web developer with a keen interest in bringing function and form together as one to create a powerful, beautiful experience for users.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s