Open In App

Web API Animations

Last Updated : 19 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Web API Animations are all about making HTML elements (like buttons, images, and text) and their styles (like colors, sizes, and positions) change over time. Web API animations are tools that help change how things look and move on websites. They make elements like buttons, images, or text shift or transform over time. These animations work with various features like controlling the speed, timing, and style changes, offering a range of effects. They involve different parts, such as creating sets of changes called keyframes, providing timelines for these changes, and triggering events when animations start, end, or repeat.

These animations are vital in making websites more engaging and interactive. Developers use them to create smoother transitions, make elements move around, or modify colors and sizes dynamically. They are compatible with many popular web browsers, allowing websites to offer dynamic, visually appealing experiences across different platforms.

Web Animations Interfaces

Web Animations facilitates several interfaces, which are described below with their brief description:

Animation Interface

  • Provides controls for playing and managing animations.
  • Offers a timeline to control the timing and duration of an animation.

KeyframeEffect

  • Enables the creation of sets of animatable properties and values known as keyframes.
  • Defines specific property changes at different points during an animation.

AnimationTimeline

  • Manages the timing and synchronization of animations.
  • Provides a timeline for sequencing and coordinating multiple animations.

AnimationEvent

  • Triggers specific events during different stages of an animation’s lifecycle.
  • Includes events like animationstart, animationend, and animationiteration.

DocumentTimeline

  • Offers a timeline for animations on the entire document.
  • Controls the playback of animations applied to the entire web page.

Web API Animations Interface Extensions

Web API animations are extensively used in web development to enhance user experiences. Here are some common use cases:

Element.getAnimations()

  • Retrieves a list of animations associated with a specific HTML element.
  • Useful for obtaining information about currently running animations on an element.

document.getAnimations()

  • Fetches a list of all currently active animations within the document.
  • Helpful for obtaining a comprehensive overview of running animations in the document.

document.timeline

  • Provides access to the timeline for document-level animations.
  • Offers control over the playback and synchronization of animations across the entire webpage.

Element.animate()

  • Initiates an animation on an HTML element, serving as the primary method for creating web animations.
  • Allows defining animation effects like property changes, duration, and timing functions.

These functionalities enable developers to create, manage, and control animations for various HTML elements, enhancing user experiences on websites. Here, we create an animation that smoothly transitions the opacity of “myElement” from 0 to 1 over a duration of 1000 milliseconds using an “ease-in-out” timing function.

element.animate([
    { opacity: 0 },
    { opacity: 1 }
], {
    duration: 1000,
    easing: "ease-in-out"
});

Approach

  • Set up the basic HTML structure, including <html>, <head>, and <body> tags.
  • Set the title of the webpage to “Rotation Animation” using the <title> element.
  • In the <style> section, apply CSS styles to center the content both vertically and horizontally on the page using Flexbox. Also, define the styling for the animated square and the button.
  • Create a button with the id “animateButton” and a square <div> with the id “animatedSquare” in the <body> section. These elements are used for the animation.
  • Select the button and square elements by their respective IDs using getElementById.
  • Add a click event listener to the button to listen for clicks.
  • When the button is clicked, the JavaScript code triggers a CSS animation on the square.
  • The animation: Rotates the square continuously from 0 degrees to 360 degrees (one full rotation, Lasts for 2 seconds. Loops infinitely, creating a continuous rotation effect.

Example: This example illustrates the illustration of the Web API Animations.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width,
                   initial-scale=1.0">
    <title>Rotation Animation</title>
    <style>
        html, body {
            height: 100%;
            margin: 0;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
  
        #animatedSquare {
            width: 100px;
            height: 100px;
            background-color: #FF5733;
            transition: transform 0.5s ease;
        }
  
        #animateButton {
            background-color: #0074d9;
            color: #fff;
            border: none;
            padding: 10px 20px;
            cursor: pointer;
        }
    </style>
</head>
  
<body>
    <button id="animateButton">
          Rotate Square
      </button>
    <div id="animatedSquare"></div>
  
    <script>
        const animateButton =
            document.getElementById('animateButton');
        const animatedSquare =
            document.getElementById('animatedSquare');
  
        animateButton.addEventListener('click', () => {
  
            // Create an animation that 
           // continuously rotates the square
            animatedSquare.animate(
                [
  
                    // Start rotation
                    { transform: 'rotate(0deg)' },
  
                    // End rotation (360 degrees)
                    { transform: 'rotate(360deg)' }
                ],
                {
                    // 2 seconds for one full rotation
                    duration: 2000,
                    iterations: Infinity, // Loop infinitely
                    easing: 'linear'  // Linear motion
                }
            );
        });
    </script>
</body>
  
</html>


Output:

Rotate-(1)

Example: This is another example that illustrates the illustration of the Web API Animations.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, 
                     initial-scale=1.0">
    <title>Animated Button</title>
    <style>
        html, body {
            height: 100%;
            margin: 0;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
  
        #animatedButton {
            width: 150px;
            height: 60px;
            background-color: #0074d9;
            color: #fff;
            border: none;
            cursor: pointer;
            transition: transform 0.3s ease;
            font-size: 18px;
        }
  
        #animatedButton:hover {
            background-color: #0056b3;
        }
    </style>
</head>
  
<body>
    <button id="animatedButton">
          Click Me!
      </button>
  
    <script>
  
        // Get a reference to the button element
        const animatedButton =
            document.getElementById('animatedButton');
  
        // Function to create and control the animation
        function animateButton() {
  
            // Create an animation effect using 
            // the Element.animate() method
            animatedButton.animate(
                [
                    // Start position
                    { transform: 'translateX(0)' },
  
                    // Move to the right
                    { transform: 'translateX(200px)' },
  
                    // Move back to the left
                    { transform: 'translateX(0)' }
                ],
                {
                    // Duration in milliseconds (2 seconds)
                    duration: 2000,
                    easing: 'linear', // Linear motion
                    iterations: Infinity // Loop infinitely
                }
            );
        }
  
        // Add a click event listener to start the animation
        animatedButton.addEventListener('click', animateButton);
    </script>
</body>
  
</html>


Output:

LeftRight-(1)-(1)

Browser Compatibility

  • Chrome 84 and above
  • Firefox 75 and above
  • Safari 13.1 and above
  • Edge 84 and above
  • Opera 71 and above


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads