[英]calculate fps of html5 canvas game with javascript
我正在创建一个 html5 canvas 游戏,并想检查一秒钟内通过了多少帧。 我尝试过使用 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
在循环 function 中检查执行之间经过的时间。
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;
}
我会使用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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.