requestAnimationFrame

by abernier

HTML

<form>
    <p>
        <label for="duration">Duration</label>
        <input id="duration" type="range" min="100" max="10000" value="1000">
    </p>
    
    <p>
        <button id="start">Play</button>
        <button id="stop">Stop</button>
    </p>
</form>

CSS

canvas {border:1px solid;}

JavaScript

(function () {

var animation = (function () {
    //
    // Our animation module
    //
    
    var canvas, ctx, size,
        animating;
    
    window.requestAnimFrame = (function (){
        //
        // requestAnim shim layer by Paul Irish
        //
        // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
        //
        
        return  window.requestAnimationFrame       || 
                window.webkitRequestAnimationFrame || 
                window.mozRequestAnimationFrame    || 
                window.oRequestAnimationFrame      || 
                window.msRequestAnimationFrame     || 
                function(/* function */ callback, /* DOMElement */ element) {
                    window.setTimeout(callback, 1000 / 60);
                };
    }());
    
    window.cancelRequestAnimFrame = (function () {
        //
        // cancelRequestAnim shim layer by Jerome Etienne
        // 
        // http://notes.jetienne.com/2011/05/18/cancelRequestAnimFrame-for-paul-irish-requestAnimFrame.html
        //
        
        return  window.cancelAnimationFrame              ||
                window.webkitCancelRequestAnimationFrame ||
                window.mozCancelRequestAnimationFrame    ||
                window.oCancelRequestAnimationFrame      ||
                window.msCancelRequestAnimationFrame     ||
                clearTimeout
    }());

    function init(options) {
        size = options.size || 256;
    
        canvas = document.createElement('canvas');
        canvas.width = canvas.height = size;
    
        ctx = canvas.getContext('2d');

        $('body').prepend(canvas);
        
        draw(0);
    
        return this;
    }

    function play(duration) {
        var start = (new Date).getTime(),
            finish = start + duration;
        
        if (animating) {
            //
            // Ensure the animation is not already being performed
            //
            
            return;
        }
 ...