用javascript计算html5canvas游戏的fps

calculate fps of html5 canvas game with javascript

我正在创建一个 html5 canvas 游戏,想检查一秒钟内通过了多少帧。我试过使用 new Date(),但它不起作用。我将如何设法做到这一点? javascript template/example:

var fps;
function loop(){
    //some code

    window.requestAnimationFrame(loop);
}
function checkFrameRate(){
    fps = //how long it takes for loop to run
    window.requestAnimationFrame(checkFrameRate);
}
loop();
checkFrameRate

在循环函数中检查执行之间经过的时间。

let lastTime = new Date();
function loop() { 
    const currentTime = new Date();
    // currentTime - lastTime is the number of milliseconds passed from last loop 
    const fps = 1000 / (currentTime - lastTime);
    lastTime = currentTime;
}

我会使用 performance.now() 而不是 new Date():

let fps;
let requestTime;

function loop(time) {
    if (requestTime) {
        fps = Math.round(1000/((performance.now() - requestTime)));
    }

    console.log(fps);
    requestTime = time;
    window.requestAnimationFrame((timeRes) => loop(timeRes));
}

window.requestAnimationFrame((timeRes) => loop(timeRes));