【问题标题】:calculate fps of html5 canvas game with javascript用javascript计算html5画布游戏的fps
【发布时间】:2020-02-04 05:01:18
【问题描述】:

我正在创建一个 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

【问题讨论】:

    标签: javascript runtime frame-rate requestanimationframe


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      我会使用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));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-02
        • 1970-01-01
        • 1970-01-01
        • 2023-04-04
        • 2013-06-08
        • 1970-01-01
        相关资源
        最近更新 更多