10.1 Animações Combinadas
Animações complexas podem melhorar significativamente a interface do usuário, tornando-a mais interativa e atraente. Para criar essas animações, costuma-se usar uma combinação de CSS e JavaScript. Vamos explorar técnicas avançadas de animação que incluem cenários mais complexos e interatividade.
Combinando várias animações usando CSS, é possível criar efeitos sofisticados. Veja um exemplo onde um elemento muda de tamanho, gira e se move simultaneamente.
Exemplo: Animações Combinadas
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Animações Combinadas</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: #3498db;
animation: combined 4s infinite alternate;
}
@keyframes combined {
0% {
transform: scale(1) rotate(0deg) translateX(0);
}
50% {
transform: scale(1.5) rotate(45deg) translateX(100px);
}
100% {
transform: scale(1) rotate(0deg) translateX(0);
}
}
</style>
</head>
<body>
<div style="min-height: 250px; padding: 20px 0;">
<div class="box"></div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Animações Combinadas</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: #3498db;
animation: combined 4s infinite alternate;
}
@keyframes combined {
0% {
transform: scale(1) rotate(0deg) translateX(0);
}
50% {
transform: scale(1.5) rotate(45deg) translateX(100px);
}
100% {
transform: scale(1) rotate(0deg) translateX(0);
}
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
Explicação do código:
.box
: elemento ao qual a animação combinada é aplicada@keyframes combined
: define a animação que altera a escala, rotação e posição do elemento
10.2 Animações com JavaScript
A função requestAnimationFrame
permite criar animações suaves com alto desempenho.
Ela sincroniza a animação com a taxa de atualização da tela, tornando-a mais fluida.
Exemplo: Animação de movimento usando requestAnimationFrame
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Animação com requestAnimationFrame</title>
<style>
.ball {
width: 50px;
height: 50px;
background-color: #e74c3c;
border-radius: 50%;
position: absolute;
}
</style>
</head>
<body>
<div style="min-height: 60px; padding: 20px 0;">
<div class="ball"></div>
</div>
<script>
const ball = document.querySelector('.ball');
let start = null;
function animate(time) {
if (!start) start = time;
let progress = time - start;
ball.style.left = Math.min(progress / 10, 200) + 'px';
if (progress < 2000) {
requestAnimationFrame(animate);
}
}
requestAnimationFrame(animate);
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Animação com requestAnimationFrame</title>
<style>
.ball {
width: 50px;
height: 50px;
background-color: #e74c3c;
border-radius: 50%;
position: absolute;
}
</style>
</head>
<body>
<div class="ball"></div>
<script>
// Seleciona o elemento com a classe "ball" e armazena na variável ball
const ball = document.querySelector('.ball');
// Variável para armazenar o tempo inicial da animação
let start = null;
// Função de animação
function animate(time) {
// Se a animação está iniciando, armazena o tempo atual
if (!start) start = time;
// Calcula o tempo decorrido desde o início da animação
let progress = time - start;
// Define a posição da bola no eixo esquerdo de acordo com o tempo decorrido
// Limita o deslocamento máximo para 200 pixels
ball.style.left = Math.min(progress / 10, 200) + 'px';
// Se menos de 2000 milissegundos se passaram, continua a animação
if (progress < 2000) {
requestAnimationFrame(animate);
}
}
// Inicia a animação
requestAnimationFrame(animate);
</script>
</body>
</html>
Explicação do código:
requestAnimationFrame
: função que chamaanimate
para executar quadros da animaçãoanimate
: função que move o elemento.ball
200 pixels para a direita em 2 segundos
10.3 Controle de Animações CSS com JavaScript
JavaScript pode ser usado para controlar animações CSS, alterando classes ou estilos de elementos.
Exemplo: Iniciar animação CSS ao clicar em um botão
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Iniciar animação com clique no botão</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: #2ecc71;
position: relative;
}
.box.animate {
animation: moveAndRotate 3s forwards;
}
@keyframes moveAndRotate {
0% {
transform: translateX(0) rotate(0deg);
}
100% {
transform: translateX(200px) rotate(360deg);
}
}
</style>
</head>
<body>
<div style="padding: 30px 0">
<div class="box" id="box"></div>
</div>
<button id="startButton">Start Animation</button>
<script>
document.getElementById('startButton').addEventListener('click', function() {
document.getElementById('box').classList.toggle('animate');
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Iniciar animação com clique no botão</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: #2ecc71;
position: relative;
}
.box.animate {
animation: moveAndRotate 3s forwards;
}
@keyframes moveAndRotate {
0% {
transform: translateX(0) rotate(0deg);
}
100% {
transform: translateX(200px) rotate(360deg);
}
}
</style>
</head>
<body>
<div class="box" id="box"></div>
<button id="startButton">Start Animation</button>
<script>
document.getElementById('startButton').addEventListener('click', function() {
document.getElementById('box').classList.toggle('animate');
});
</script>
</body>
</html>
Explicação do código:
.box.animate
: classe que adiciona a animação moveAndRotate ao elemento.box
-
JavaScript: evento
click
no botão#startButton
adiciona ou remove a classeanimate
do elemento#box
, iniciando a animação
10.4 Interação com Animações através de Eventos
Eventos de animação, como animationstart
, animationend
e animationiteration
, permitem rastrear e gerenciar animações.
Exemplo: Rastreamento de eventos de animação
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rastreamento de eventos de animação</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: #9b59b6;
animation: scaleUp 2s infinite;
}
@keyframes scaleUp {
0% {
transform: scale(1);
}
50% {
transform: scale(1.5);
}
100% {
transform: scale(1);
}
}
</style>
</head>
<body>
<div class="box" id="box"></div>
<script>
const box = document.getElementById('box');
box.addEventListener('animationstart', () => {
console.log('Animação iniciada');
});
box.addEventListener('animationend', () => {
console.log('Animação terminada');
});
box.addEventListener('animationiteration', () => {
console.log('Iteração da animação');
});
</script>
</body>
</html>
Explicação do código:
animationstart
: evento que dispara no início da animaçãoanimationend
: evento que dispara no final da animaçãoanimationiteration
: evento que dispara a cada repetição da animação
GO TO FULL VERSION