简体   繁体   中英

calculate fps of html5 canvas game with javascript

I am creating a html5 canvas game and want to check how many frames pass in one second. I have tried using new Date(), and it is not working. How would I manage to do this? javascript template/example:

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

In the loop function check the time passed between executions.

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;
}

I would use performance.now() instead of 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM