Beyond Static: CSS Animation
Sobre a Aula

Dynamic manipulation of animations

In this topic, we will explore the dynamic manipulation of animations in integration with JavaScript. The idea is to create animations that respond dynamically to user interactions or changes in the application’s state.

Smooth Transitions with CSS

To begin, we can use CSS transitions to create smooth animations. Transitions are perfect for simple states, such as changes in color, size, or position.

Let’s see an example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    .box {
      width: 100px;
      height: 100px;
      background-color: blue;
      transition: background-color 0.5s ease;
    }

    .box:hover {
      background-color: red;
    }
  </style>
</head>
<body>
  <div class="box"></div>
</body>
</html>

In this example, the background color of the box changes smoothly when the cursor passes over it.

Animations with JavaScript

For greater control, we can use JavaScript to manipulate animations. Let’s create a simple example using the Anime.js library:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.0/anime.min.js"></script>
</head>
<body>
  <div id="animatedBox" style="width: 100px; height: 100px; background-color: green;"></div>

  <script>
    const box = document.getElementById('animatedBox');

    anime({
      targets: box,
      translateX: 250,
      easing: 'easeInOutQuad',
      duration: 1000
    });
  </script>
</body>
</html>

This code uses the Anime.js library to animate the translation of the box to the right when the page is loaded.

Responses to Events

We can also link animations to user events. Let’s create a simple example with a button:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    .box {
      width: 100px;
      height: 100px;
      background-color: orange;
      transition: transform 0.5s ease;
    }
  </style>
</head>
<body>
  <div class="box"></div>
  <button onclick="animateBox()">Mover Caixa</button>

  <script>
    function animateBox() {
      const box = document.querySelector('.box');
      box.style.transform = 'translateX(200px)';
    }
  </script>
</body>
</html>

In this example, when clicking the button, the box moves to the right.

In summary, dynamic animation manipulation allows for creating more interactive and responsive interfaces, enhancing the user experience.

Whether using CSS transitions, libraries like Anime.js, or responding to events, integration with JavaScript opens up a range of possibilities for dynamic animations in your web applications.

Entrar na conversa
Rolar para cima