Javascript Animation

What is animation?

Animation is a mechanism that creates a video-like effect using a group of pictures, which shows movement. Basically, animation takes some pictures and arranges them to make a video. In the IT industry, various languages support animation with different properties, and Javascript is one of those languages that support animation in web development.

Manual Animation

The process is not automated in manual animation; we use javascript DOM methods to access the elements. The implementation process of manual animation is as follows,

  1. We get the element using the getElementById() method which returns the element used in the webpage.
  2. Then we have to initialize a function init(), which initializes imgObj where we have to set the position.
  3. This function gets called when the window loads.
  4. Finally, we call moveRight() to set some animation.

Automated Animation

In Automated animation we can automate the process using setTimeOut() method as follows,

  1. The moveRight() function calls setTimeOut() to set the position of imgObj.
  2. Also we have added a new method stop() to clear the time set by setTimeOut() and set the object at initial position.

Advantages of Animation

  1. You can visually represent your abstract ideas : like you want to create some kind of machine, but the company is not ready for it, you can show them a graphical view.
  2. You can show a big thing in a small and effective way.
  3. You can bring any idea to life, which is not possible in real life.

Example No.1:

<html> <style> #container { width: 400px; height: 400px; position: relative; background: yellow; } #animate { width: 50px; height: 50px; position: absolute; background-color: red; } </style> <body> <p><button onclick="myMove()">Click Me</button></p> <div id ="container"> <div id ="animate"></div> </div> <script> function myMove() { let id = null; const elem = document.getElementById("animate"); let pos = 0; clearInterval(id); id = setInterval(frame, 5); function frame() { if (pos == 350) { clearInterval(id); } else { pos++; = pos + "px"; = pos + "px"; } } } </script> </body> </html>