The word fps is usually associated with videos and games where we need to use animation. fps is the abbreviation of frames per second and represents the number of times the current screen is re-rendered.
For example, a video is a continuous row of images. This means that it displays images at very short intervals so the user has no way of knowing that it is displaying images individually. If we lower the fps of the video, it may look like an image animation instead of a video. Therefore, higher fps gives better results. Basically, fps tells us how many times in a second the screen should be updated.
Sometimes, we need to use JavaScript to control fps. There are different methods we can use, which we will learn in this tutorial.
The setTimeout() function takes the callback function as the first parameter and the time interval as the second parameter. Here we can control fps by re-rendering the screen after each time interval.
Users can use the setTimeout() function to control fps according to the following syntax.
setTimeout(() => { requestAnimationFrame(animate); }, interval);
We used the requestAnimationFrame() method to call the animate() function in the above syntax.
Step 1 - Define the totalFrames variable and initialize it to zero. It will record the total number of frames.
Step 2 - Additionally, define the fps variable and store the value of fps.
Step 3 - Define intervalOffps variable and store intervals into it. It stores 1000/fps where 1000 is milliseconds and we get the time interval by dividing it by fps.
Step 4 - Store the current time in the startTime variable.
Step 5 - Call the animate() function.
Step 5.1 - Call the requestAnimationFrame() function using the setTimeout() function after each internvalOffps.
Step 5.2 - In the callback function of the setTimeout() function, the user can write code to re-render the screen or draw shapes on the Canvas.
Step 5.3 - Use a Date() object and get the current time. Subtract the start time from the current time to get the elapsed time.
Step 5.4 - Using math functions, get the total fps and total time.
In the following example, we use the setTimeout() function to control fps. We use "3" as the value for fps. Therefore, our fps interval is equal to 1000/3. Therefore, we will call the requestAnimationFrame() method every 1000/3 milliseconds.
<html> <body> <h3> Using the <i> setTimeOut() method </i> to control the fps with requestAnimationFrame </h3> <div id="output"> </div> <script> let output = document.getElementById("output"); // Initial frame count set to zero var totalFrames = 0; var current, consumedTime; // Set the fps at which the animation will run (say 10 fps) var fps = 3; var intervalOffps = 1000 / fps; var AfterTime = Date.now(); var starting = AfterTime; animate(); function animate() { setTimeout(() => { // call the animate function recursively requestAnimationFrame(animate); // get current time current = Date.now(); // get elapsed time since the last frame var elapsed = current - starting; //Divide elapsed time with frame count to get fps var currentFps = Math.round((1000 / (elapsed / ++totalFrames)) * 100) / 100; output.innerHTML = "Total elapsed time is equal to = " + Math.round((elapsed / 1000) * 100) / 100 + "<br>" + " secs @ "; output.innerHTML += currentFps + " fps."; }, intervalOffps); } </script> </body> </html>
We can use the Date() object to get the difference between the current time and the previous frame time. If the time difference exceeds the frame interval, we will re-render the screen. Otherwise, we wait for a single frame to complete.
Users can use the time interval to control the frame rate according to the following syntax.
consumedTime = current - AfterTime; if (consumedTime > intervalOffps) { // rerender screen }
In the above syntax, the elapsed time is the difference between the current time and the time when the last frame was completed.
In the example below, we take the time difference between the current frame and the last frame. If the time difference is greater than the time interval, we re-render the screen.
<html> <body> <h3> Using the <i> Date() object </i> to control the fps with requestAnimationFrame. </h3> <div id = "output"> </div> <script> let output = document.getElementById("output"); // Initial framecount set to zero var totalFrames = 0; var current, consumedTime; // Set the fps at which the animation will run (say 10 fps) var fps = 50; var intervalOffps = 1000 / fps; var AfterTime = Date.now(); var starting = AfterTime; animate(); function animate() { // use date() object and requestAnimationFrame() to control fps requestAnimationFrame(animate); current = Date.now(); consumedTime = current - AfterTime; // if the consumed time is greater than the interval of fps if (consumedTime > intervalOffps) { // draw on canvas here AfterTime = current - (consumedTime % intervalOffps); var elapsed = current - starting; //Divide elapsed time with frame count to get fps var currentFps = Math.round((1000 / (elapsed / ++totalFrames)) * 100) / 100; output.innerHTML = "Total elapsed time is equal to = " + Math.round((elapsed / 1000) * 100) / 100 + "<br>" + " secs @ "; output.innerHTML += currentFps + " fps."; } } </script> </body> </html>
In the example below, the user can set the fps using the input range. Afterwards, when the user clicks the button, it executes the startAnimation() function, which sets the fps interval and calls the animate() function. The animate() function calls the drawShape() function to draw shapes on the canvas and control fps.
Here, we use some methods to draw shapes on the canvas. Users can use the input range to change the fps, try animating shapes and observe the difference in animation.
<html> <body> <h3>Using the <i> Date() object </i> to control the fps with requestAnimationFrame. </h3> <!-- creating an input range for fps --> <input type = "range" min = "1" max = "100" value = "10" id = "fps" /> <button onclick = "startAnimation()"> Animate </button> <br><br> <!-- canvas to draw shape --> <canvas id = "canvas" width = "250" height = "250"> </canvas> <script> let canvas = document.getElementById("canvas"); let context = canvas.getContext("2d"); let animation; let intervalOffps, current, after, elapsed; let angle = 0; // drawing a sha[e] function drawShape() { context.save(); context.translate(100, 100); // change angle context.rotate(Math.PI / 180 * (angle += 11)); context.moveTo(0, 0); // draw line context.lineTo(250, 250); context.stroke(); context.restore(); // stop animation if (angle >= 720) { cancelAnimationFrame(animation); } } function animate() { // start animation and store its id animation = requestAnimationFrame(animate); current = Date.now(); elapsed = current - after; // check if elapsed time is greater than interval, if yes, draw shape again if (elapsed > intervalOffps) { after = current - (elapsed % intervalOffps); drawShape(); } } function startAnimation() { // get fps value from input let fpsInput = document.getElementById("fps"); let fps = fpsInput.value; // calculate interval intervalOffps = 1000 / fps; after = Date.now(); requestAnimationFrame(animate); } </script> </body> </html>
The above is the detailed content of How to control fps using requestAnimationFrame?. For more information, please follow other related articles on the PHP Chinese website!