Thursday, December 26, 2024
Google search engine

ES6 | Animation

In ES6 JavaScript, Animation can be done in two ways. The ES6 JavaScript can be used to move <div>, <img>, and so many other HTML element. 
 

  • Using setInterval() Method: The setInterval() method of JavaScript takes two arguments. A function and an Integer. It is terminated using clearInterval() method.
  • Using requestAnimationFrame() Method: The requestAnimationFrame() method takes single argument function. It will run the function when the screen is ready to accept the next repaint. So, calling requestAnimationFrame()method only once turns out to be pretty meaningless. The animated effect occurs when we call it recursively, then the desired animation is created frame by frame, each frame called when the browser is ready for it. 
     

Using setInterval() Method: This method is traditionally used to produce animation effects through JavaScript. This relies on repeatedly executing some code to make changes in the element frame by frame.
 

anim = setInterval(fn, t);
    The function fn is called after every t milliseconds.
clearInterval(anim);
    It terminates the above process.

Example: If the function fn produces a change in element style, setInterval(function, t) can be used to produce gradual changes in element style after every time interval. If the time interval is small enough, the changes look continuous, thereby producing an animating effect.
 

html




<!DOCTYPE html>
<html>
 
<head>
    <title>
        ES6 | Animation
    </title>
 
    <style>
        #background {
            width: 400px;
            height: 400px;
            position: relative;
            background: black;
        }
        #block {
            width: 50px;
            height: 50px;
            position: absolute;
            background-color: white;
            border: 2px red solid;
        }
    </style>
</head>
 
<body>
    <center>
     
    <h1 style="color:green">neveropen</h1>
 
    <div id="background">
        <div id="block"></div>
    </div>
     
    <br>
     
    <button onclick="animation()">Click here</button>
 
    <script>
        function animation() {
            var can = document.getElementById("block");
            var i = 0;
             
            // Call after 10 ms
            var id = setInterval(makeframe, 10);
         
            function makeframe() {
 
                // Terminate at boundaries
                if (i == 347) {
                    clearInterval(id);
                }
                else {
                    i++;
                         
                    // Setting the top style
                    can.style.top = i + 'px';
 
                    // Setting the left style
                    can.style.left = i + 'px';
                }
            }
        }
    </script>
    </center>
</body>
 
</html>


Output: 
 

Disadvantages: 
 

  • The time interval(t) specified may not comply with the user system resources, leading to inconsistent delay between the frames.
  • Usage of setInterval() leads to a condition called Layout Thrashing.

Using requestAnimationFrame() Method: The disadvantages encountered in using setInterval() lead to the introduction of the requestAnimationFrame() method. The method allows you to execute code on the next available screen repaint, thereby getting in sync with the user’s browser and hardware readiness to make changes to the screen.
 

function makeframe {
    ..... ......          
    requestAnimationFrame(makeframe); // Recursive call          
}          
makeframe(); // Initiation          

Here the termination is brought about by the function cancelAnimationFrame(). The total functioning of the animation along with its termination is shown below. 
 

function makeframe {          
    ..... ......          
    if(.. ..){cancelAnimationFrame(anim);} // Termination          
    anim = requestAnimationFrame(makeframe); // Recursive call          
}          
makeframe(); // Initiation

Generally, requestAnimationFrame() runs at 60 fps. To slow the rate of it, we can use setTimeout() function. Its functioning is shown below. 
 

function makeframe {          
    var rate = fps;          
    setTimeout(function() { // Timeout use  
        ..... ......          
        if(.. ..) {cancelAnimationFrame(anim);} // Termination          
        anim = requestAnimationFrame(makeframe); // Recursive call          
    }, 1000/rate);          
}          
makeframe(); // Initiation          

Example: Here the most comfortable way to slow down/speed up the animation is to adjust the magnitude of change in each frame. 
 

html




<!DOCTYPE html>
<html>
 
<head>
    <title>ES6 | Animation</title>
     
    <style>
        #background {
            width: 200px;
            height: 200px;
            position: relative;
            background: black;
        }
         
        #block {
            width: 50px;
            height: 50px;
            position: absolute;
            background-color: white;
            border: 2px red solid;
        }
    </style>
</head>
 
<body>
    <center>
     
    <h1 style="color:green;">neveropen</h1>
     
    <div id="background">
        <div id="block"></div>
    </div>
     
    <br>
     
    <button onclick="animation()">Click here</button>
 
    <script>
        function animation() {
            var can = document.getElementById("block");
            var i = 0;
            var rate = 30;
 
            function makeframe() {
                setTimeout(function() {
                    var anim =
                        requestAnimationFrame(makeframe);
                     
                    if (i == 146) {
                         
                        // Terminate at boundaries    
                        cancelAnimationFrame(anim);
                    }
                    else {
                        i++;
                         
                        // Setting the top style
                        can.style.top = i + 'px';
                         
                         // Setting the left style
                        can.style.left = i + 'px';
                    }
                }, 1000 / rate);
            }
            makeframe();
        }
    </script>
    </center>
</body>
 
</html>


Output: 
 

Note: Both the methods when used ably could be used to create very complex animations (e.g that can be used in Game Development ). 
Supported Browsers: The browsers supported by ES6 animation are listed below: 
 

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Safari
  • Opera

 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments