Canvas Animation base code

JavaScript

// current application time, in milliseconds.
var applicationTime = 0;

// scale applied to time. 
// 1 means no scale, <1 is slower, >1 faster.
var timeSpeed = 1;

// --------------------------------------------
//  Those 3 methods (draw/handleInput/update)
//     will get called on each rAF
// --------------------------------------------

function draw() {}

function handleInput() {}

function update(dt)  {}

// -------------- run !! ------------------

launchAnimation();

// ---------------------------------------

// after launchAnimation is called, 
// (draw/handleInput/update)
//     will get called on each rAF
function launchAnimation() {
    requestAnimationFrame(_launchAnimation);
}

// ------------- Private methods ----------------

function _launchAnimation(now) {
    _lastTime = now;
    applicationTime = 0
    requestAnimationFrame(_animate);
}

// ----------------------------------------------
// Animation.
//   Use launchAnimate() to start the animation.
//     draw, handleInput, update will be called every frame.
// ----------------------------------------------
function _animate(now) {
    requestAnimationFrame(_animate);
    // _______________________
    var dt = now - _lastTime;
    if (dt < 12) return; // 60 HZ max
    if (dt > 200) dt = 16; // consider 1 frame elapse on tab-out 
    _lastTime = now;
    dt *= timeSpeed;
    applicationTime += dt;
    // _______________________
    handleInput(); // ...
    // update everything with this frame time step.
    update(dt);
    // draw everything    
    draw();
}
var _lastTime = 0;

// requestAnimationFrame polyfill    
(function polyFillRAFNow() {
    var w = window;
    if (!w.requestAnimationFrame) {
        var m = 'RequestAnimationFrame';
        w.requestAnimationFrame = w['webkit' + m] || ['ms' + m] || w['moz' + m] || w['o' + m];
    }
})();

function voidFunction() {};