Animating the Web: A Beginner's Guide to Creating Stunning Animations

ยท

12 min read

Animating the Web: A Beginner's Guide to Creating Stunning Animations

What are animations?

Animations refer to the dynamic and visually appealing movements, transitions, or transformations of elements on a website or web application. Animations are used to enhance user experience, provide visual feedback, guide user attention, and create engaging interactions.

Animations can involve various properties and effects, such as:

  1. Movement: Animating the position of elements, making them slide, scroll, or translate across the screen.

  2. Opacity: Animating the transparency or opacity of elements, creating fade-in or fade-out effects.

  3. Size: Animating the size of elements, allowing them to expand, shrink, or scale in response to user actions or events.

  4. Colour: Animating the colour of elements, smoothly transitioning between different hues or shades.

  5. Rotation: Animating the rotation of elements, causing them to spin, flip, or rotate around a specific axis.

  6. Transition: Applying smooth transitions to CSS properties, gradually changing values over a specified duration.

These can be triggered by various events, such as user interactions (hover, click), page loading, or as part of a scrolling effect.

Why should we use animations?

  1. Enhancing User Experience: Animations can make the user interface more engaging, intuitive, and enjoyable to interact with. They provide visual feedback, guide users through transitions, and communicate changes effectively. Well-designed animations can create a seamless and delightful user experience.

  2. Providing Visual Feedback: Animations can convey changes and interactions in a more intuitive way than static elements. For example, a button changing colour or size on hover or click provides immediate feedback to the user, indicating that an action has been triggered. Visual feedback helps users understand the state of the application and their interactions with it.

  3. Guiding User Attention: Animations can direct the user's focus and attention to specific elements or content. By using subtle motion or highlighting effects, designers can draw attention to important information, calls to action, or key features. Animations can guide users through a user interface and improve the overall usability of the application.

  4. Conveying Information and Context: Animations can effectively communicate information, transitions, and relationships between elements. For instance, animated charts or data visualizations can present complex data in a more digestible and visually appealing manner. Animations can also help in storytelling, illustrating concepts, or demonstrating processes.

  5. Creating a Polished and Professional Look: Well-executed animations contribute to the overall aesthetic appeal and professionalism of a website or application. Smooth and visually pleasing animations can elevate the perception of quality, attention to detail, and modernity in front-end design.

  6. Showcasing Interactivity and Responsiveness: Animations can showcase the interactivity and responsiveness of an application, making it feel more dynamic and alive. Loading spinners, progress bars, or content transitions can provide visual cues that the application is actively responding to user input or performing actions.

What are the three states of animations?

The three states of animation are typically referred to as the starting state, intermediate state, and ending state. These states represent the different stages or keyframes that define the animation's progression. Here's a breakdown of each state:

  1. Starting State: This is the initial state of the animation before any animation effects or transformations are applied. It represents the state of the element or elements before the animation begins. The starting state serves as the basis from which the animation will evolve.

  2. Intermediate States: These states define the various stages or keyframes during the animation's progression. Intermediate states specify how the elements should appear at specific points in time, allowing for smooth transitions between states. By defining multiple intermediate states, an animation can achieve complex and dynamic transformations.

  3. Ending State: This is the final state of the animation, representing how the elements should appear at the end of the animation. The ending state defines the ultimate position, size, colour, or other properties of the elements after the animation is completed. It establishes the desired outcome of the animation.

By defining these three states, animations can create fluid and visually appealing transitions from the starting state to the ending state. The intermediate states serve as waypoints, allowing for nuanced changes and transformations throughout the animation's timeline.

How to make animations?

Animations can be implemented using CSS animations, CSS transitions, or JavaScript animation libraries/frameworks.

Animations made using CSS and JavaScript differ in several ways, including their implementation, control, and flexibility. Here are some key distinctions:

Implementation:

  • CSS Animations: CSS animations are defined within CSS stylesheets using the @keyframes rule and properties like animation or transition. They are declared in the CSS file and are separate from the JavaScript code. CSS animations are primarily handled by the browser's rendering engine, which optimizes performance and offloads the animation computation.

  • JavaScript Animations: JavaScript animations are created by manipulating CSS properties using JavaScript code. Animations are programmatically defined and controlled using JavaScript functions and APIs. JavaScript provides more dynamic control over the animation logic and allows for complex calculations, event listeners, and interactivity.

Control and Interactivity:

  • CSS Animations: CSS animations have predefined start and end states and are primarily triggered by events like hover, click, or class changes. They are more suitable for static or pre-defined animations. CSS animations offer limited control over dynamic changes during animation, and their control is mostly declarative.

  • JavaScript Animations: JavaScript animations offer more granular control and interactivity. They can be triggered by various events and can dynamically change properties, respond to user input, or interact with other elements on the page. JavaScript animations allow for more complex animations with conditional logic, sequencing, and interactive behaviours.

Flexibility and Complexity:

  • CSS Animations: CSS animations are best suited for simple, straightforward animations with predefined transitions or keyframes. They are well-suited for basic effects like fading, scaling, or translating elements. CSS animations are easier to implement and maintain for simple cases.

  • JavaScript Animations: JavaScript animations provide greater flexibility and control, making them suitable for more complex and custom animations. JavaScript animations can involve advanced calculations, physics-based motion, SVG animations, and integration with external libraries. They are better suited for animations that require real-time data updates, interactive elements, or advanced effects.

In a nutshell: CSS animations are convenient for basic, predefined animations triggered by events or class changes, while JavaScript animations offer more control, flexibility, and interactivity, making them suitable for complex and dynamic animations. The choice between CSS and JavaScript animations depends on the specific requirements and complexity of the animation you want to create.

Using CSS Animations Property

  • CSS can be used to create simple animations directly in your HTML and CSS code using the animation CSS property.

  • CSS animations allow you to define keyframes and specify the properties that change over time.

  • By applying CSS classes or using JavaScript to trigger class additions/removals, you can control when the animations occur.

Let's see a few examples of it:

  1. Creating an animation that gradually fades an element from transparent to fully visible for 1 second.

     .fade-in {
       animation: fade-in 1s ease-in;
     }
    
     @keyframes fade-in {
       from { opacity: 0; }
       to { opacity: 1; }
     }
    
  2. Creating an animation that rotates an element continuously in a clockwise direction over 2 seconds.

     .spin {
       animation: spin 2s linear infinite;
     }
    
     @keyframes spin {
       from { transform: rotate(0deg); }
       to { transform: rotate(360deg); }
     }
    
  3. Creating an animation that scales an element up to 1.2 times its original size and then returns it to its original size for 0.5 seconds.

     .scale {
       animation: scale 0.5s ease-out;
     }
    
     @keyframes scale {
       0% { transform: scale(1); }
       50% { transform: scale(1.2); }
       100% { transform: scale(1); }
     }
    
  4. Creating an animation that moves an element horizontally by 200 pixels to the right and then back to its original position, creating a continuous back-and-forth movement for 3 seconds.

     .move {
       animation: move 3s linear infinite;
     }
    
     @keyframes move {
       0% { transform: translateX(0); }
       50% { transform: translateX(200px); }
       100% { transform: translateX(0); }
     }
    

Using CSS Transitions Property

CSS transitions enable you to smoothly animate property changes over a specified duration.

By applying transition properties to elements, such as opacity, size, or position, you can create subtle animations triggered by events like hover or click.

Let's see a few examples of it:

  1. Animate when you hover over the element with the class "box," the background colour smoothly transitions from blue to red over 0.3 seconds.

     .box {
       background-color: blue;
       transition: background-color 0.3s ease-in-out;
     }
    
     .box:hover {
       background-color: red;
     }
    
  2. Animate when you hover over the element with the class "box," it smoothly transitions from a width and height of 100px to 200px over 0.3 seconds.

     .box {
       width: 100px;
       height: 100px;
       transition: width 0.3s ease-in-out, height 0.3s ease-in-out;
     }
    
     .box:hover {
       width: 200px;
       height: 200px;
     }
    
  3. Animate when "show" is added class to the element with the class "box," it smoothly transitions from an opacity of 0 to 1 over 0.5 seconds, creating a fade-in effect.

     .box {
       opacity: 0;
       transition: opacity 0.5s ease-in-out;
     }
    
     .box.show {
       opacity: 1;
     }
    
  4. Animate when the "show" class is added to the element with the class "box," it slides in from the left, transitioning from a translation of -100% to 0 over 0.3 seconds.

     .box {
       transform: translateX(-100%);
       transition: transform 0.3s ease-in-out;
     }
    
     .box.show {
       transform: translateX(0);
     }
    

Using Vanilla JavaScript:

Let's see how to build this animation using plain JavaScript:

HTML

<div id="box"></div>
<button onclick="animateBox()">Animate</button>

CSS:

#box {
  width: 100px;
  height: 100px;
  background-color: blue;
  position: relative;
}

button{
  margin: 10px;
}

JavaScript:

function animateBox() {
  var box = document.getElementById("box");
  var position = 0;
  var interval = setInterval(moveBox, 10);

  function moveBox() {
    if (position >= 200) {
      clearInterval(interval);
    } else {
      position += 1;
      box.style.left = position + "px";
    }
  }
}

In the above example, we have an HTML element <div> with the id "box" and a button with an onclick event that triggers the animateBox() JavaScript function.

The JavaScript function animateBox() selects the element with the id "box" using getElementById(). It then initializes a variable position to track the current position of the box and starts an interval using setInterval() to repeatedly call the moveBox() function every 10 milliseconds.

Inside the moveBox() function, we check if the box has reached the desired position (in this case, 200 pixels). If it has, we stop the animation by clearing the interval using clearInterval(). If not, we increment the position by 1 and update the left CSS property of the box to move it horizontally.

By clicking the "Animate" button, the box will gradually move 200 pixels to the right, creating a simple animation effect.

PS: This is a very basic example, and JavaScript animations can be much more complex and versatile. You can animate different properties, combine multiple animations, create custom easing functions, and integrate with external animation libraries for more advanced effects.

Using JavaScript Libraries

Let's see how to build this animation using gsap:

HTML:

<div class="container">
    <div class="tomato">
        <img src="https://image-dock-uploads-be.s3.ap-south-1.amazonaws.com/image.2022-09-12T02%3A18%3A50.164Z"
             width="100px"
             height="100px"
          />
    </div>
</div>

CSS:


.container {
  border: 1px solid black;
  width: 500px;
  height: 100px;
  align-items: center;
  display: flex;
  padding: 30px;
  margin-bottom: 30px;
  position: relative;
}

JavaScript:

const box = document.getElementsByClassName("tomato");

// TweenMax is a function from GSAP
TweenMax.to(box, 4, {
  repeat: Infinity,
  keyframes: {
    "0%": {
      x: 0,
    },
    "48%": {
      rotationY: "0deg",
    },
    "50%": {
      x: 400,
      rotationY: "180deg",
    },
    "98%": {
      rotationY: "180deg",
    },
    "100%": {
      x: 0,
      rotationY: "0deg",
    },
  },
});

Tips to make Animations Performant

  1. Use GPU Acceleration: Offloading animations to the GPU (Graphics Processing Unit) can significantly improve performance. To trigger GPU acceleration, utilize CSS properties like transform and opacity instead of animating properties that trigger layout changes, such as width, height, or top. Transformations and opacity changes can be hardware accelerated, leading to smoother animations.

  2. Use will-change Property: The will-change CSS property informs the browser in advance that an element will change, allowing it to optimize rendering. Apply will-change to elements you plan to animate, specifying the properties that will change during the animation. For example:

     .box {
       will-change: transform, opacity;
     }
    
  3. Minimize DOM Manipulation: Animations that involve frequent changes to the DOM structure can be costly in terms of performance. Strive to minimize DOM manipulation during animations by using techniques like CSS transforms, opacity changes, or animating pseudo-elements instead of adding/removing elements from the DOM.

  4. Use animation instead of transition for Complex Animations: For complex animations with multiple keyframes or complex timing functions, using the animation property instead of transition can provide better performance. animation allows more control over the animation timeline and enables you to define easing functions and keyframes directly within CSS.

  5. Limit Animations on Page Load: Restrict animations that occur immediately on page load, as they can hinder initial rendering and increase perceived load time. Instead, consider triggering animations on user interaction or after the initial page load to ensure a smoother initial rendering.

  6. Test and Optimize Performance: Test your animations across different devices, browsers, and screen sizes to ensure optimal performance. Monitor animation performance using browser developer tools and consider using tools like Lighthouse or WebPageTest to identify performance bottlenecks and optimize your animations further.

  7. Limit Animations to Specific Elements: Applying animations to a large number of elements simultaneously can strain performance. Be mindful of the number of elements being animated and limit animations to specific elements or targeted sections of your webpage.

Conclusion

In conclusion, animations play a crucial role in web development, enriching user experiences, providing visual feedback, and enhancing interactions. Whether it's a subtle fade-in effect or a complex interactive animation, well-implemented animations can captivate users, guide their attention, and bring life to web interfaces.

CSS animations, CSS transitions, and JavaScript-based libraries like GSAP and Framer Motion offer powerful tools for creating animations. CSS animations provide a declarative approach, allowing for smooth and efficient animations through GPU acceleration and optimized property choices. CSS transitions enable simple property changes over a specified duration, while JavaScript libraries provide advanced features and interactivity.

When using animations it's important to consider performance, choosing properties that can be hardware accelerated and minimizing layout changes that trigger rendering calculations. Careful selection of animated properties, aligned with user interactions and the visual impact desired, can greatly enhance the overall user experience.

Remember, animations should be used purposefully, enhancing usability and providing meaningful visual cues. Strive for consistency with your overall design language and consider accessibility implications to ensure inclusivity.

By mastering the art of animations you can create engaging and delightful user experiences, making your web applications stand out and leave a lasting impression on users. So, let your creativity flourish and explore the world of animations to bring your front-end projects to life. Happy Coding! :)

Here are some captivating articles/resources worth exploring

  1. https://csstriggers.com/

  2. https://web.dev/animations-overview/

  3. https://youtu.be/4PStxeSIL9I

The following tools were utilized in the creation of this blog:

  1. Canva (canva.com): This platform was used to design the blog cover, providing an aesthetically pleasing visual representation.

  2. OpenAI Chat (chat.openai.com): OpenAI's Chat tool played a vital role in content polishing, assisting in refining the text and improving its overall quality.