Calculate FPS in Canvas using requestAnimationFrame

前端 未结 10 2258
滥情空心
滥情空心 2020-11-30 00:31

How could I calculate the FPS of a canvas game application? I\'ve seen some examples, but none of them use requestAnimationFrame, and im not sure how to apply their solution

10条回答
  •  囚心锁ツ
    2020-11-30 01:08

    I have a different approach, because if you calculate the the FPS you'll get this flickering when returning the number. I decided to count every Frame and return it once a second

    window.countFPS = (function () {
      var lastLoop = (new Date()).getMilliseconds();
      var count = 1;
      var fps = 0;
    
      return function () {
        var currentLoop = (new Date()).getMilliseconds();
        if (lastLoop > currentLoop) {
          fps = count;
          count = 1;
        } else {
          count += 1;
        }
        lastLoop = currentLoop;
        return fps;
      };
    }());
    
    requestAnimationFrame(function () {
      console.log(countFPS());
    });
    

    jsfiddle

提交回复
热议问题