Table of Contents
Use the SetTime() function
grammar
step
Example 3
Using the Date() object
Home Web Front-end JS Tutorial How to control fps using requestAnimationFrame?

How to control fps using requestAnimationFrame?

Aug 29, 2023 am 08:41 AM

如何使用 requestAnimationFrame 控制 fps?

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.

1

2

3

setTimeout(() => {

   requestAnimationFrame(animate);

}, interval);

Copy after login

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

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

Copy after login

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.

1

2

3

4

consumedTime = current - AfterTime;

if (consumedTime > intervalOffps) {

   // rerender screen

}

Copy after login

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

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

Copy after login

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

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

Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Custom Google Search API Setup Tutorial Custom Google Search API Setup Tutorial Mar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

Build Your Own AJAX Web Applications Build Your Own AJAX Web Applications Mar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Example Colors JSON File Example Colors JSON File Mar 03, 2025 am 12:35 AM

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

8 Stunning jQuery Page Layout Plugins 8 Stunning jQuery Page Layout Plugins Mar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

What is 'this' in JavaScript? What is 'this' in JavaScript? Mar 04, 2025 am 01:15 AM

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

Improve Your jQuery Knowledge with the Source Viewer Improve Your jQuery Knowledge with the Source Viewer Mar 05, 2025 am 12:54 AM

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 Mobile Cheat Sheets for Mobile Development 10 Mobile Cheat Sheets for Mobile Development Mar 05, 2025 am 12:43 AM

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

See all articles