Animations with JS

Animations on Web using JavaScript.

If you have ever done animations on Javascript then you might be aware of setInterval().
If you haven't perform animations on Javascript and  want to, then you might want to use something like setInterval().But interval is not reliable as it seems and a more suitable API is now available...

var elem = document.getElementById("animatedElem"), 
    left = 0, 
    timer; 

// Move the element 10px on the right every 16ms 
timer = setInterval(function() { 
    elem.style.left = ( left += 10 ) + "px"; 
    // clear the timer at 400px to stop the animation 
    if ( left == 400 ) { 
        clearInterval( timer ); 
    } 
}, 16);

A game based on this logic would run normally, but if the animations were too complex or running on a low-spec device, then game experience would be altered.To animate at constant speed, we need to calculate the time delta since the last frame and move the element proportionally.

But now browser vendors have decided to give developers an API for animation. And that is a very good decision because browser vendors can probably optimize things for us.
That API is requestAnimationFrame (rAF). It's a basic API for use with animation, whether that be DOM-based styling changes, canvas or WebGL.

With "rAF", The browser can optimize concurrent animations together into a single reflow and repaint cycle, leading to higher fidelity animation.Also, if you're running the animation loop in a tab that's not visible, the browser won't keep it running, which means less CPU, GPU, and memory usage, leading to much longer battery life.

window.requestAnimationFrame tells the browser that you wish to perform an animation and requests that the browser schedule a repaint of the window for the next animation frame. The method takes as an argument a callback to be invoked before the repaint.

How to use it?
// shim layer with setTimeout fallback 
window.requestAnimFrame = (function(){ 
    return window.requestAnimationFrame || 
           window.webkitRequestAnimationFrame || 
           window.mozRequestAnimationFrame || 
           window.oRequestAnimationFrame || 
           window.msRequestAnimationFrame || 
           function( callback ){ 
               window.setTimeout(callback, 1000 / 60); 
           };
})(); 

// usage: 
// instead of setInterval(render, 16) .... 

(function animloop()
    requestAnimFrame(animloop); 
    render(); 
})(); 

// place the rAF *before* the render() to assure as close to 
// 60fps with the setTimeout fallback.

The way we use clearInterval() which Cancels repeated actions set with setInterval(), same way we can also do it with cancelAnimationFrame() which Cancels an animation frame request previously scheduled through a call to requestAnimationFrame().

A polyfill is here:
(function() {
var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] 
                                   || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); }, 
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());


[References]
1)http://www.html5rocks.com/en/tutorials/canvas/performance/
2)http://paulirish.com/2011/requestanimationframe-for-smart-animating/
3)http://hacks.mozilla.org/2011/08/animating-with-javascript-from-setinterval-to-requestanimationframe/
4)http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
5)https://developer.mozilla.org/en-US/docs/DOM/window.requestAnimationFrame
6)https://gist.github.com/1579671#file-raf-js-L8

Comments

Popular Posts