小编典典

使用requestAnimationFrame控制fps?

javascript

现在看来似乎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();
    }
}

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


阅读 713

收藏
2020-05-01

共1个答案

小编典典

如何将requestAnimationFrame限制为特定帧速率

演示以5 FPS的速度节流:http :
//jsfiddle.net/m1erickson/CtsY3/

此方法通过测试自执行最后一个帧循环以来的经过时间来工作。

仅当指定的FPS间隔过去时,图形代码才会执行​​。

代码的第一部分设置了一些用于计算经过时间的变量。

var stop = false;
var frameCount = 0;
var $results = $("#results");
var fps, fpsInterval, startTime, now, then, elapsed;


// initialize the timer variables and start the animation

function startAnimating(fps) {
    fpsInterval = 1000 / fps;
    then = Date.now();
    startTime = then;
    animate();
}

这段代码是实际的requestAnimationFrame循环,以您指定的FPS绘制。

// the animation loop calculates time elapsed since the last loop
// and only draws if your specified fps interval is achieved

function animate() {

    // request another frame

    requestAnimationFrame(animate);

    // calc elapsed time since last loop

    now = Date.now();
    elapsed = now - then;

    // if enough time has elapsed, draw the next frame

    if (elapsed > fpsInterval) {

        // Get ready for next frame by setting then=now, but also adjust for your
        // specified fpsInterval not being a multiple of RAF's interval (16.7ms)
        then = now - (elapsed % fpsInterval);

        // Put your drawing code here

    }
}
2020-05-01