相关疑难解决方法(0)

使用requestAnimationFrame控制fps?

这似乎requestAnimationFrame是现在制作动画的事实上的方式.在大多数情况下,它对我来说效果很好,但是现在我正在尝试做一些画布动画,我想知道:有没有办法确保它以某个fps运行?我知道rAF的目的是为了一贯平滑的动画,我可能冒着使我的动画不稳定的风险,但是现在看起来它的速度几乎是任意的,并且我想知道是否有办法打击不知何故.

我使用setInterval但我想要rAF提供的优化(特别是当选项卡处于焦点时自动停止).

如果有人想查看我的代码,它几乎是:

animateFlash: function() {
    ctx_fg.clearRect(0,0,canvasWidth,canvasHeight);
    ctx_fg.fillStyle = 'rgba(177,39,116,1)';
    ctx_fg.strokeStyle = 'none';
    ctx_fg.beginPath();
    for(var i in nodes) {
        nodes[i].drawFlash();
    }
    ctx_fg.fill();
    ctx_fg.closePath();
    var instance = this;
    var rafID = requestAnimationFrame(function(){
        instance.animateFlash();
    })

    var unfinishedNodes = nodes.filter(function(elem){
        return elem.timer < timerMax;
    });

    if(unfinishedNodes.length === 0) {
        console.log("done");
        cancelAnimationFrame(rafID);
        instance.animate();
    }
}
Run Code Online (Sandbox Code Playgroud)

其中Node.drawFlash()只是一些代码,它根据计数器变量确定半径,然后绘制一个圆.

javascript performance animation canvas requestanimationframe

111
推荐指数
8
解决办法
9万
查看次数

requestAnimationFrame在函数的开头或结尾?

如果我有一个使用requestAnimationFrame的循环,如下所示:

function render() {
    // Rendering code

    requestAnimationFrame(render);
}
Run Code Online (Sandbox Code Playgroud)

如果我把requestAnimationFrame函数放在函数的开头,会有什么区别,如下所示:

function render() {
    requestAnimationFrame(render);

    // Rendering code
}
Run Code Online (Sandbox Code Playgroud)

我没有注意到任何差异,但我已经看到两种实现,其中一种更好,或者它们是否相同?

编辑:我想到的一件事是,如果我把它放在开头,并且渲染代码需要很长时间才能运行,比如说10毫秒,最终不会把它放到帧速率下降10毫秒?

javascript requestanimationframe

12
推荐指数
3
解决办法
2741
查看次数