Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Achieve somewhat stable framerate with requestAnimationFrame?

I am playing around with the requestAnimationFrame but I get very jerky animations in any other browser than Chrome.

I create an object like this:

var object = function() {

    var lastrender = (new Date()).getTime();
    var delta = 0;

    return {

        update: function() {
             //do updates using delta value in calculations.
        },

        loop: function() {
            var looptimestamp = (new Date()).getTime();
            delta = looptimestamp - lastrender;
            lastrender = looptimestamp;

            this.update();

            window.requestAnimationFrame(this.loop.bind(this));
        }
    };
}

Right now I am just drawing a single rectangle on a canvas element and moving it around. It is a very lightweight operation on the processor. This is running pretty smoothly in Chrome, and when I console log the delta value, it is almost consistant around ~17. However, if I do the same in Firefox or Safari I get the following delta values:

17-3-17-2-32-34-32-31-19-31-17-3-0-14-3-14-35-31-16-3-17-2 ... and so on

It looks as if the browser is not syncing with the display very nicely, and in all other cases than Chrome, one would get smoother animations using the old setTimeout method with 16ms as the target timeout.

Does anyone know, if it is possible to get smoother animations using requestAnimationFrame in browsers other than Chrome? Has anyone succeded in getting more stable delta values than the ones posted above in Firefox?

like image 712
acrmuui Avatar asked May 15 '13 09:05

acrmuui


1 Answers

The reason the smooth framerate of your animation decreases is because of the memory of your browser with regards to the canvas. I don't know the real details of the performance in browsers but firefox almost immediately has a framerate drop and in chrome the drop occurs some time later.

The real problem of the framerate drop is because of the memory occupied by the canvas element. Each time you draw something to the canvas that operation is saved to the path of the canvas. This path occupies more memory each time you draw something on the canvas. If you don't empty the path of the canvas you will have framerate drops. The canvas path can't be emptied by clearing the canvas with context.clearRect(x, y, w, h);, instead you have to reset the canvas path by beginning a new path with context.beginPath();. For example:

// function that draws you content or animation
function draw(){
    // start a new path/empty canvas path
    canvas.beginPath(); 

    // actual drawing of content or animation here 
}
like image 182
Joszs Avatar answered Sep 20 '22 14:09

Joszs