首页 > 解决方案 > 用javascript计算html5画布游戏的fps

问题描述

我正在创建一个 html5 画布游戏,并想检查一秒钟内通过了多少帧。我尝试过使用 new Date(),但它不起作用。我将如何做到这一点?javascript模板/示例:

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

标签: javascriptruntimeframe-raterequestanimationframe

解决方案


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

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;
}

推荐阅读