Calculate FPS in Canvas using requestAnimationFrame

前端 未结 10 2247
滥情空心
滥情空心 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

    Actually none of the answers were sufficient for me. Here is a better solution which:

    • Use's performance.now()
    • Calculates the actual average fps per second
    • Average per second and decimal places are configurable

    Code:

    // Options
    const outputEl         = document.getElementById('fps-output');
    const decimalPlaces    = 2;
    const updateEachSecond = 1;
    
    // Cache values
    const decimalPlacesRatio = Math.pow(10, decimalPlaces);
    let timeMeasurements     = [];
    
    // Final output
    let fps = 0;
    
    const tick = function() {
      timeMeasurements.push(performance.now());
    
      const msPassed = timeMeasurements[timeMeasurements.length - 1] - timeMeasurements[0];
    
      if (msPassed >= updateEachSecond * 1000) {
        fps = Math.round(timeMeasurements.length / msPassed * 1000 * decimalPlacesRatio) / decimalPlacesRatio;
        timeMeasurements = [];
      }
    
      outputEl.innerText = fps;
    
      requestAnimationFrame(() => {
        tick();
      });
    }
    
    tick();
    

    JSFiddle

提交回复
热议问题