Animações Lottie
Visão Geral
Lottie é uma biblioteca para renderizar animações do After Effects em tempo real na web, iOS, Android e React Native. Criada pela Airbnb, permite que designers enviem animações tão facilmente quanto enviam assets estáticos. As animações são exportadas do After Effects como arquivos JSON usando o plugin Bodymovin e, em seguida, renderizadas nativamente com sobrecarga mínima de desempenho.
Quando usar Lottie:
- Animações criadas por designers que precisam de fidelidade de pixel perfeita
- Ícones animados complexos e micro-interações
- Animações de carregamento e indicadores de progresso
- Sequências de integração e animações tutoriais
- Animações de marketing e conteúdo promocional
- Alternativa a GIF/vídeo com tamanhos de arquivo menores e escalabilidade
Principais vantagens:
- Baseado em vetores (escalável sem perda de qualidade)
- Tamanhos de arquivo significativamente menores que GIF ou vídeo
- Editável em tempo de execução (cores, velocidade, segmentos)
- Controle total do designer via After Effects
- Consistência de renderização entre plataformas
- Controles interativos (play, pause, seek, loop)
Conceitos Principais
Tipos de Formato Lottie
1. JSON Lottie (.json)
- Formato Lottie original
- Exportado do After Effects via plugin Bodymovin
- Estrutura JSON legível por humanos
- Tamanhos de arquivo maiores (não compactado)
- Amplamente suportado em todas as plataformas
2. dotLottie (.lottie)
- Formato compactado moderno
- Arquivo ZIP contendo JSON + assets
- Suporta múltiplas animações e temas em um único arquivo
- Tamanhos de arquivo menores (até 90% de redução)
- Recomendado para uso em produção
Opções de Biblioteca
lottie-web (biblioteca original):
import lottie from 'lottie-web';
lottie.loadAnimation({
container: document.getElementById('lottie-container'),
renderer: 'svg', // ou 'canvas', 'html'
loop: true,
autoplay: true,
path: 'animation.json' // ou animationData: jsonData
});
@lottiefiles/dotlottie-web (moderna, recomendada):
import { DotLottie } from '@lottiefiles/dotlottie-web';
new DotLottie({
canvas: document.getElementById('canvas'),
src: 'animation.lottie',
autoplay: true,
loop: true
});
@lottiefiles/dotlottie-react (integração React):
import { DotLottieReact } from '@lottiefiles/dotlottie-react';
<DotLottieReact
src="animation.lottie"
loop
autoplay
style={{ height: 300 }}
/>
lottie-react (wrapper React alternativo):
import Lottie from 'lottie-react';
import animationData from './animation.json';
<Lottie animationData={animationData} loop={true} />
Fontes de Dados de Animação
1. LottieFiles (lottie.host)
- Mais de 100.000 animações gratuitas
- Incorporação direta por URL
- Hospedagem CDN
2. Arquivos JSON/dotLottie locais
- Empacotados com a aplicação
- Melhor desempenho (sem requisição de rede)
- Amigável ao controle de versão
3. Exportação do After Effects
- Animações personalizadas do designer
- Plugin Bodymovin necessário
- Configurações de exportação críticas para o tamanho do arquivo
Padrões Comuns
1. Integração HTML Básica com dotLottie-web
<!DOCTYPE html>
<html>
<head>
<style>
#canvas {
width: 400px;
height: 400px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="module">
import { DotLottie } from 'https://cdn.jsdelivr.net/npm/@lottiefiles/dotlottie-web/+esm';
new DotLottie({
canvas: document.getElementById('canvas'),
src: 'https://lottie.host/4db68bbd-31f6-4cd8-84eb-189de081159a/IGmMCqhzpt.lottie',
autoplay: true,
loop: true
});
</script>
</body>
</html>
2. Componente React com Controles
import React from 'react';
import { DotLottieReact } from '@lottiefiles/dotlottie-react';
const AnimatedButton = () => {
const [dotLottie, setDotLottie] = React.useState(null);
const handlePlay = () => dotLottie?.play();
const handlePause = () => dotLottie?.pause();
const handleStop = () => dotLottie?.stop();
const handleSeek = (frame) => dotLottie?.setFrame(frame);
return (
<div>
<DotLottieReact
src="button-animation.lottie"
loop
autoplay={false}
dotLottieRefCallback={setDotLottie}
style={{ height: 200 }}
/>
<div>
<button onClick={handlePlay}>Play</button>
<button onClick={handlePause}>Pause</button>
<button onClick={handleStop}>Stop</button>
<button onClick={() => handleSeek(30)}>Seek to frame 30</button>
</div>
</div>
);
};
3. Listeners de Eventos e Hooks de Ciclo de Vida
import React, { useEffect } from 'react';
import { DotLottieReact } from '@lottiefiles/dotlottie-react';
const EventDrivenAnimation = () => {
const [dotLottie, setDotLottie] = React.useState(null);
useEffect(() => {
if (!dotLottie) return;
const onLoad = () => console.log('Animation loaded');
const onPlay = () => console.log('Animation started');
const onPause = () => console.log('Animation paused');
const onComplete = () => console.log('Animation completed');
const onFrame = ({ currentFrame }) => console.log('Frame:', currentFrame);
dotLottie.addEventListener('load', onLoad);
dotLottie.addEventListener('play', onPlay);
dotLottie.addEventListener('pause', onPause);
dotLottie.addEventListener('complete', onComplete);
dotLottie.addEventListener('frame', onFrame);
return () => {
dotLottie.removeEventListener('load', onLoad);
dotLottie.removeEventListener('play', onPlay);
dotLottie.removeEventListener('pause', onPause);
dotLottie.removeEventListener('complete', onComplete);
dotLottie.removeEventListener('frame', onFrame);
};
}, [dotLottie]);
return (
<DotLottieReact
src="animation.lottie"
loop
autoplay
dotLottieRefCallback={setDotLottie}
/>
);
};
4. Animação Orientada por Scroll com lottie-react
import Lottie from 'lottie-react';
import robotAnimation from './robot.json';
const ScrollAnimation = () => {
const interactivity = {
mode: 'scroll',
actions: [
{
visibility: [0, 0.2],
type: 'stop',
frames: [0]
},
{
visibility: [0.2, 0.45],
type: 'seek',
frames: [0, 45]
},
{
visibility: [0.45, 1.0],
type: 'loop',
frames: [45, 60]
}
]
};
return (
<Lottie
animationData={robotAnimation}
style={{ height: 300 }}
interactivity={interactivity}
/>
);
};
5. Reprodução de Segmento Acionada por Hover
import { useLottie, useLottieInteractivity } from 'lottie-react';
import likeButton from './like-button.json';
const HoverAnimation = () => {
const lottieObj = useLottie({
animationData: likeButton
});
const Animation = useLottieInteractivity({
lottieObj,
mode: 'cursor',
actions: [
{
position: { x: [0, 1], y: [0, 1] },
type: 'loop',
frames: [45, 60]
},
{
position: { x: -1, y: -1 },
type: 'stop',
frames: [45]
}
]
});
return <div style={{ height: 300, border: '2px solid black' }}>{Animation}</div>;
};
6. Suporte a Múltiplas Animações e Temas
import { DotLottieReact } from '@lottiefiles/dotlottie-react';
import React, { useState, useEffect } from 'react';
const ThemedAnimation = () => {
const [dotLottie, setDotLottie] = useState(null);
const [animations, setAnimations] = useState([]);
const [themes, setThemes] = useState([]);
const [currentAnimationId, setCurrentAnimationId] = useState('');
const [currentThemeId, setCurrentThemeId] = useState('');
useEffect(() => {
if (!dotLottie) return;
const onLoad = () => {
setAnimations(dotLottie.manifest.animations || []);
setThemes(dotLottie.manifest.themes || []);
setCurrentAnimationId(dotLottie.activeAnimationId);
setCurrentThemeId(dotLottie.activeThemeId);
};
dotLottie.addEventListener('load', onLoad);
return () => dotLottie.removeEventListener('load', onLoad);
}, [dotLottie]);
return (
<div>
<DotLottieReact
src="multi-animation.lottie"
dotLottieRefCallback={setDotLottie}
animationId={currentAnimationId}
themeId={currentThemeId}
/>
{themes.length > 0 && (
<select value={currentThemeId} onChange={(e) => setCurrentThemeId(e.target.value)}>
{themes.map((theme) => (
<option key={theme.id} value={theme.id}>{theme.id}</option>
))}
</select>
)}
{animations.length > 0 && (
<select value={currentAnimationId} onChange={(e) => setCurrentAnimationId(e.target.value)}>
{animations.map((anim) => (
<option key={anim.id} value={anim.id}>{anim.id}</option>
))}
</select>
)}
</div>
);
};
7. Web Worker para Desempenho (DotLottieWorker)
import { DotLottieWorker } from '@lottiefiles/dotlottie-web';
// Descarrega a renderização da animação para um web worker
new DotLottieWorker({
canvas: document.getElementById('canvas'),
src: 'heavy-animation.lottie',
autoplay: true,
loop: true,
workerId: 'worker-1' // Agrupa múltiplas animações por worker
});
// Múltiplas animações em workers separados
new DotLottieWorker({
canvas: document.getElementById('canvas-2'),
src: 'animation-2.lottie',
autoplay: true,
loop: true,
workerId: 'worker-2'
});
Padrões de Integração
Com GSAP ScrollTrigger
import Lottie from 'lottie-react';
import gsap from 'gsap';
import ScrollTrigger from 'gsap/ScrollTrigger';
import animationData from './animation.json';
gsap.registerPlugin(ScrollTrigger);
const GSAPLottieIntegration = () => {
const lottieRef = React.useRef();
React.useEffect(() => {
const anim = lottieRef.current;
if (!anim) return;
// Sincroniza Lottie com o scroll
gsap.to(anim, {
scrollTrigger: {
trigger: '#animation-section',
start: 'top center',
end: 'bottom center',
scrub: 1,
onUpdate: (self) => {
const frame = Math.floor(self.progress * (anim.totalFrames - 1));
anim.goToAndStop(frame, true);
}
}
});
}, []);
return (
<div id="animation-section" style={{ height: '200vh' }}>
<Lottie
lottieRef={lottieRef}
animationData={animationData}
autoplay={false}
loop={false}
/>
</div>
);
};
Com Framer Motion
import { motion } from 'framer-motion';
import { DotLottieReact } from '@lottiefiles/dotlottie-react';
const MotionLottie = () => {
return (
<motion.div
initial={{ opacity: 0, scale: 0.8 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.6 }}
>
<DotLottieReact
src="animation.lottie"
loop
autoplay
style={{ height: 400 }}
/>
</motion.div>
);
};
Integração com Vue 3
<script setup>
import { DotLottieVue } from '@lottiefiles/dotlottie-vue';
</script>
<template>
<DotLottieVue
style="height: 500px; width: 500px"
autoplay
loop
src="https://path-to-animation.lottie"
/>
</template>
Integração com Svelte
<script lang="ts">
import { DotLottieSvelte } from '@lottiefiles/dotlottie-svelte';
import type { DotLottie } from '@lottiefiles/dotlottie-svelte';
let dotLottie: DotLottie | null = null;
function play() {
dotLottie?.play();
}
</script>
<DotLottieSvelte
src="animation.lottie"
loop={true}
autoplay={true}
dotLottieRefCallback={(ref) => dotLottie = ref}
/>
<button on:click={play}>Play</button>
Otimização de Desempenho
Otimização de Tamanho de Arquivo
1. Configurações de Exportação no After Effects:
- Ativar "Skip images that aren't used"
- Usar "Glyphs" em vez de fontes quando possível
- Simplificar paths (reduzir pontos no illustrator)
- Evitar efeitos que criam grandes dados (partículas, ruído)
- Usar shape layers em vez de vector layers
2. Compressão:
- Usar formato dotLottie (.lottie) para compressão automática
- Executar JSON através de ferramentas de otimização Lottie
- Remover metadados desnecessários
3. Carregamento Lazy:
const LazyLottie = () => {
const [shouldLoad, setShouldLoad] = React.useState(false);
React.useEffect(() => {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
setShouldLoad(true);
}
});
observer.observe(document.getElementById('lottie-trigger'));
return () => observer.disconnect();
}, []);
return (
<div id="lottie-trigger">
{shouldLoad && <DotLottieReact src="animation.lottie" loop autoplay />}
</div>
);
};
Desempenho em Tempo de Execução
1. Seleção de Renderizador:
// SVG: Melhor qualidade, mais lento para animações complexas
// Canvas: Melhor desempenho, rasterizado
// HTML: Suporte limitado, use apenas para animações simples
// Para animações complexas, prefira canvas
new DotLottie({
canvas: document.getElementById('canvas'),
src: 'animation.lottie',
autoplay: true,
loop: true,
renderConfig: {
devicePixelRatio: window.devicePixelRatio || 1
}
});
2. Web Workers:
// Descarregar para worker em animações pesadas
import { DotLottieWorker } from '@lottiefiles/dotlottie-web';
new DotLottieWorker({
canvas: document.getElementById('canvas'),
src: 'heavy-animation.lottie',
autoplay: true,
loop: true
});
3. Otimização para Dispositivos Móveis:
// Reduzir qualidade em dispositivos móveis
const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
new DotLottie({
canvas: document.getElementById('canvas'),
src: isMobile ? 'animation-low.lottie' : 'animation-high.lottie',
autoplay: true,
loop: true,
renderConfig: {
devicePixelRatio: isMobile ? 1 : window.devicePixelRatio
}
});
Armadilhas Comuns
1. Vazamentos de Memória por Limpeza Incorreta
Problema: Não destruir instâncias Lottie quando componentes são desmontados.
Solução:
const SafeAnimation = () => {
const [dotLottie, setDotLottie] = React.useState(null);
…