Calculate FPS in Canvas using requestAnimationFrame

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

    My fps calculation uses requestAnimationFrame() and the matching timestamp argument for its callback function.
    See https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame and https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp.

    No need for new Date() or performance.now()!

    The rest is inspired heavily by other answers in this thread, especially https://stackoverflow.com/a/48036361/4706651.

    var fps = 1;
    var times = [];
    var fpsLoop = function (timestamp) {
        while (times.length > 0 && times[0] <= timestamp - 1000) {
            times.shift();
        }
        times.push(timestamp);
        fps = times.length;
        console.log(fps);
        requestAnimationFrame(fpsLoop);
    }
    
    requestAnimationFrame(fpsLoop);

提交回复
热议问题