FPS mit RequestAnimationFrame

by joquery

HTML

<canvas id="mycanvas" width="300" height="200"></canvas>

CSS

canvas{
    border: 3px solid #fd3300;
}

JavaScript

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

(function(window, document, undefined){

    var canvas       = document.getElementById("mycanvas"),
        context      = canvas.getContext("2d"),
        width        = canvas.width,
        height       = canvas.height,
        fps          = 0,
        game_running = true,
        show_fps     = true,
        oldtime = +new Date

    function showFPS(time){
        context.fillStyle = "Black";
        context.font      = "normal 16pt Arial";

        context.fillText(fps + " fps", 10, 26);
    }
    function gameLoop(time){

        //Clear screen
        context.clearRect(0, 0, width, height);
        fps = 1000/(time-oldtime)
        oldtime = time;

        if (show_fps) showFPS();

        if (game_running) requestAnimFrame(gameLoop);

    }
    
    gameLoop();

}(this, this.document))