【问题标题】: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));