How to control fps using requestAnimationFrame?
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.
Use the SetTime() function
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.
grammar
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
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.
Example 1
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>
Using the Date() object
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.
grammar
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.
Example 2
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>
Example 3
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
