Sometimes, we want to calculate frames per second (FPS) in the canvas using JavaScript’s requestAnimationFrame function.
In this article, we’ll look at how to calculate FPS in the canvas using JavaScript’s requestAnimationFrame function.
Calculate FPS in the Canvas Using JavaScript’s requestAnimationFrame Function
To calculate FPS in the canvas using JavaScript’s requestAnimationFrame function, we can create our own function that gets the number of timestamps that are added to an array in one second.
Then the length of that array is the FPS value.
To do this, we write:
let fps = 1;
const times = [];
const fpsLoop = (timestamp) => {
while (times.length > 0 && times[0] <= timestamp - 1000) {
times.shift();
}
times.push(timestamp);
fps = times.length;
console.log(fps);
requestAnimationFrame(fpsLoop);
}
requestAnimationFrame(fpsLoop);
We create the times
array to hold the array of timestamps.
Then the length of times
is the FPS value.
Next, we create the fpsLoop
to remove the entries in the times
array is times[0]
is less than or equal to timestamp — 1000
and times.length
is bigger than 0 to remove the timestamps that are added before 1 second.
Then we push the timestamp
into the times
array.
And we assign times.length
to fps
to get the FPS value.
Next, we call requestAnimation
with fpsLoop
to run the function indefinitely.
And we call requestAnimation
with fpsLoop
in the last line to start the measurement.
Conclusion
To calculate FPS in the canvas using JavaScript’s requestAnimationFrame function, we can create our own function that gets the number of timestamps that are added to an array in one second.
Then the length of that array is the FPS value.