Achieve somewhat stable framerate with requestAnimationFrame?

匆匆过客 提交于 2020-01-23 05:16:41

问题


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?


回答1:


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 
}



回答2:


You might get smoother animation if you skip updates when delta < threshold, for example:

if (delta > 5) this.update();


来源:https://stackoverflow.com/questions/16561214/achieve-somewhat-stable-framerate-with-requestanimationframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!