banner



How Would I Randomize An Animation For Javascript

Blithe counters are a not bad way to testify statistics on your website considering interactive elements meliorate the user feel. Blithe counters can be used to bear witness your site visits, members registered, or show some numbers in your online game.

While this could otherwise be implemented using some static dull numbers. Animated counters help us give our sites an expressive and professional look.

JavaScript has helper methods that when artistically manipulated can help united states of america accomplish that in a very easy fashion. Nosotros tin exercise this in a few statements using a framework or library, only it's ameliorate to create i for ourselves from scratch and understand the underlying code. Information technology too gives us an upper hand in customizing the code and adding more functionalities ourselves.

Overview

We only need to use a few JavaScript helper methods and gear up the duration for the animation. The JavaScript methods used (which we volition discuss in more detail further on) are:

  • Math.min()
  • Math.floor()
  • window.requestAnimationFrame()
  • window.cancelAnimationFrame()

Allow's begin coding an blithe counter similiar to the i illustrated beneath:

Illustration

The JavaScript code

The full code can exist accessed at my Github Repository.

                          function              animate(obj,              initVal,              lastVal,              duration) {              let              startTime              =              null;              //get the current timestamp and assign it to the currentTime variable                                          let              currentTime              =              Appointment.now();              //laissez passer the current timestamp to the step function                                          const              step              =              (currentTime              ) => {              //if the start time is null, assign the electric current fourth dimension to startTime                                          if              (!              startTime) {              startTime              =              currentTime              ;         }              //calculate the value to exist used in calculating the number to be displayed                                          const              progress              =              Math.min((currentTime              -              startTime)              /              duration,              ane);              //calculate what to exist displayed using the value gotten above                                          obj.innerHTML              =              Math.floor(progress              *              (lastVal              -              initVal)              +              initVal);              //checking to make sure the counter does non exceed the last value (lastVal)                                          if              (progress              <              1) {               window.requestAnimationFrame(step);         }              else{               window.cancelAnimationFrame(window.requestAnimationFrame(footstep));         }     };              //start animating                                          window.requestAnimationFrame(step); }              let              text1              =              document.getElementById('0101');              let              text2              =              document.getElementById('0102');              let              text3              =              certificate.getElementById('0103');              const              load              =              () => {              breathing(text1,              0,              907,              5000);              animate(text2,              0,              432,              5000);              animate(text3,              100,              12,              5000); }                      

Caption

Nosotros take 3 user-defined functions:

  1. breathing()
  2. footstep()
  3. load()

The animate() role is a higher-order function containing the step() function.

This function takes four parameters:

  1. A DOM object(obj).

  2. Initial value which the counter will start with(initVal).

  3. Terminal value which the counter volition terminate with (lastVal).

  4. The duration in milliseconds which the animation volition last (duration).

The breathing function has a variable startTime initialized to null. This variable stores the timestamp when the counter starts. It also has a currentTime variable that stores the latest timestamp as the counter executes. Next, nosotros take the step() office which is used to compute the number to be displayed, where information technology is displayed, and controls the blitheness.

The beginning if block assigns the showtime of the counter to startTime. It negates startTime to get a true value if startTime is aught and and then assigns information technology the current start time. The constant progress stores a value that will set up the interval betwixt the previous and adjacent number which should not exceed 1.

Information technology does and so by subtracting the offset timestamp from the current timestamp then dividing information technology past the duration. Since it does not have to be greater than 1 (one,2,3,4,…), nosotros apply the Math.min method which usually returns the lowest value from its parameters. The interval number does not need to change throughout the lifetime of the step role hence nosotros brand it a const.

A mathematical case The next statement subtracts the first value from the last value, multiplies the respond gotten past the interval so adds the first value basing on the operator precedence e.chiliad. for a reducing counter.

Current timestamp = 202018500

Start timestamp = 202018200

(202018500 - 202018200) = 300

300/5000 = 0.06

0 - 100 = -100

-100 * 0.06 = -half-dozen

-6 + 100 = 94

At the timestamp 202018500 the counter will have reduced to 94

The Math.flooring function rounds the number to a whole number lower than the parameter given. It then sets the content of obj to the number through the innerHTML property. The second if cake stops the counter once the interval is greater than 1.

The window.requestAnimationFrame() and window.cancelAnimationFrame()

The window.requestAnimationFrame() method is used when we demand to show an blitheness. It instructs the browser to update the animation through a callback function information technology takes in, in our case, the step() function.

The window.cancelAnimationFrame() cancels an animation to exist called past taking the animation frame request ID as a parameter. The load() functions assigns text1, text2 and text3 DOM objects gotten past their respective IDs. It is chosen when the HTML torso loads using the <body> onload attribute. This is shown in the HTML code below. It uses the animate() function to set the values and perform the counter.

The HTML code

Below is the HTML code. We used Bootstrap 5 for the styling.

            <html>    <head>       <meta              name              =              "viewport"              content              =              "width=device-width, initial-scale=ane.0">       <championship>Animation counter</title>    </head>    <link              href              =              "https://cdn.jsdelivr.net/npm/bootstrap@five.0.0-beta1/dist/css/bootstrap.min.css"              rel              =              "stylesheet"              integrity              =              "sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1"              crossorigin              =              "anonymous">    <manner>       .container{              background-color:              #6f4e37;       }              p{              text-align:              heart;       }    </style>    <body              onload              =              "load()">       <p>       <div              class              =              "d-flex justify-content-center fs-one fw-bold ">Blitheness Counter</div>       </p>       <p>       <div              course              =              "container">          <div              class              =              "row">             <div              form              =              "col-sm">                <p              id              =              '0101'              grade              =              "fs-2 text-light">0</p>                <p              class              =              "text-light">Site visits</p>             </div>             <div              class              =              "col-sm">                <p              id              =              '0102'              course              =              "fs-2 text-calorie-free">876</p>                <p              class              =              "text-lite">Members signed</p>             </div>             <div              class              =              "col-sm">                <p              class              =              "fs-ii text-light"><span              id              =              '0103'>12</span>%</p>                <p              class              =              "text-lite align-content-center">Average mutter rate</p>             </div>          </div>       </div>       </p>    </torso> </html>                      

Although nosotros have used JavaScript in this tutorial, you can likewise achieve this with pure CSS. Nosotros volition talk about that in another tutorial.

That's all for now. I promise you got a helpful insight into how to create animated counters using JavaScript. Subsequently, you can enhance this counter further past changing the durations, numbers, or fifty-fifty implement information technology for words rather than digits.


Peer Review Contributions by: Peter Kayere

Source: https://www.section.io/engineering-education/javascript-animation-counter/

Posted by: fierropornat.blogspot.com

0 Response to "How Would I Randomize An Animation For Javascript"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel