通过requestAnimationFrame方法简单计算帧率,代码如下:
var calculateFPS = (function() {
var lastTime = 0;
var fps = 0;
var count = 0;
var callback;
return function calcFPS() {
if (count++ === 100) {
calcFPS.callback(fps);
}
var now = +(new Date());
var newFps = 1000 / (now - lastTime);
lastTime = now;
if (!fps) {
fps = newFps;
requestAnimationFrame(calcFPS);
} else {
if (Math.abs(fps - newFps) < 1e-6) {
calcFPS.callback(fps);
} else {
fps = newFps;
requestAnimationFrame(calcFPS);
}
}
}
})();
calculateFPS.callback = (fps) => {
console.log(fps)
}
calculateFPS()