Communitygithub.com

Animação Lottie

Habilidade para integrar, controlar e exportar animações Lottie (JSON ou .lottie) em web, iOS, Android e React Native, incluindo reprodução, interatividade, temas e otimização.

O que é Animação Lottie?

Esta habilidade cobre todo o fluxo de trabalho com animações Lottie, desde a integração básica até o controle avançado de reprodução e exportação. Ela explica a diferença entre os formatos `.json` (bruto do Bodymovin) e `.lottie` (compactado, preferível para produção) e recomenda o uso do runtime moderno `@lottiefiles/dotlottie-web` em vez do legado `lottie-web`. A habilidade fornece exemplos práticos de código para vanilla JavaScript, React, iOS, Android e React Native, incluindo controle de reprodução (play, pause, setSpeed, setFrame, setSegment), animação baseada em scroll (sem necessidade de bibliotecas extras), interatividade declarativa com `@lottiefiles/lottie-interactivity`, e recolorização em tempo de execução via temas Lottie ou override manual de cores. Também aborda otimização (preferir `.lottie`, lazy-load, IntersectionObserver) e um processo de verificação com um 'seek harness' (parâmetro `?t=N`) para congelar frames exatos para screenshots, garantindo fidelidade visual e ausência de artefatos.

Funciona com~Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/nehakanjamala/personal_website/tree/HEAD/.agents/skills/lottie-animation

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

O que Animação Lottie faz?

A ponte do After Effects para o produto: animação vetorial enviada como JSON (ou .lottie compactado), pequena e independente de resolução, reproduzida por um runtime na web, iOS, Android e React Native. Esta habilidade cobre integração, controle e exportação de Lottie.

Quando usar

  • Enviar uma animação do AE de um designer para web/iOS/Android/React Native
  • Ilustrações em loop, onboarding, estados vazios, ícones animados
  • Reprodução vetorial baseada em scroll ou interação (hover, clique, cursor)
  • Tematização/recoloração em tempo de execução em vez de reexportar por marca

Formatos: .json vs .lottie

  • .json — a saída bruta do Bodymovin. Legível para humanos, maior.
  • .lottie — um contêiner compactado (geralmente 60–80% menor) que pode agrupar múltiplas animações, imagens e temas. Preferível para envio. Player: @lottiefiles/dotlottie-web (moderno, canvas + WASM) substitui o antigo lottie-web.

Prefira o runtime dotLottie para novos trabalhos; use lottie-web apenas para necessidades legadas com .json + renderizador SVG.

Fluxo de trabalho principal (web, dotLottie)

npm i @lottiefiles/dotlottie-web        # vanilla
npm i @lottiefiles/dotlottie-react      # React wrapper

Vanilla:

import { DotLottie } from "@lottiefiles/dotlottie-web";

const dotLottie = new DotLottie({
  canvas: document.querySelector("#lottie"),  // um elemento <canvas>
  src: "/hero.lottie",                         // ou .json
  loop: true,
  autoplay: true,
  // speed: 1, mode: "forward" | "reverse" | "bounce", renderConfig: { autoResize: true }
});

React:

import { DotLottieReact } from "@lottiefiles/dotlottie-react";

function Hero() {
  return <DotLottieReact src="/hero.lottie" loop autoplay style={{ width: 320 }} />;
}

Capture a instância para controlá-la:

const [dl, setDl] = useState(null);
<DotLottieReact src="/icon.lottie" dotLottieRefCallback={setDl} />;
// dl?.play(); dl?.pause(); dl?.setSpeed(2);

Controle de reprodução

dotLottie.play();
dotLottie.pause();
dotLottie.stop();
dotLottie.setSpeed(1.5);
dotLottie.setMode("bounce");        // forward | reverse | bounce | reverse-bounce
dotLottie.setFrame(42);             // pular para um frame
dotLottie.setSegment(30, 90);       // limitar a reprodução a um intervalo de frames (ex.: loop de "carregamento")

Eventos direcionam sequenciamento e UI:

dotLottie.addEventListener("load", () => { /* totalFrames agora disponível */ });
dotLottie.addEventListener("complete", () => { /* reprodução sem loop terminou */ });
dotLottie.addEventListener("frame", ({ currentFrame }) => { /* por frame */ });

Estilo máquina de estados (ex.: botão que reproduz o segmento "marcado" e depois fica ocioso): reproduza um segmento, ouça complete, então setSegment para o loop ocioso.

Lottie baseado em scroll (sem necessidade de GSAP)

Mapeie o progresso do scroll (0–1) para um frame. Pause o autoplay e controle os frames manualmente.

const dotLottie = new DotLottie({ canvas, src: "/scroll.lottie", autoplay: false });
let total = 0;
dotLottie.addEventListener("load", () => { total = dotLottie.totalFrames; });

window.addEventListener("scroll", () => {
  const el = canvas.closest(".scrolly");
  const rect = el.getBoundingClientRect();
  const p = clamp(-rect.top / (rect.height - window.innerHeight), 0, 1); // 0..1 através da seção
  dotLottie.setFrame(p * (total - 1));
}, { passive: true });

const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));

Para interação mais rica (hover-para-reproduzir, clique alterna, cursor segue) sem escrever a fiação, use @lottiefiles/lottie-interactivity, que mapeia modos scroll, hover, click, play e cursor para intervalos de frames declarativamente.

Tematização / recolorização em tempo de execução

Dois caminhos:

  • Temas dotLottie: um .lottie pode incorporar temas de cores nomeados; alterne com dotLottie.setTheme("dark") / loadTheme(...). Criado nas ferramentas LottieFiles — sem reexportar para recolorir.
  • Sobrescrita manual de cores: carregue o JSON, percorra layers[].shapes[] e corrija os arrays de cores c.k (RGBA normalizado 0–1), depois inicialize o player com o objeto modificado. Frágil (depende da estrutura de camadas) — prefira temas ou renderizador SVG orientado a CSS (lottie-web rendererSettings) quando precisar reestilizar por classe.

Runtimes móveis (paridade)

  • iOS — lottie-ios (LottieAnimationView): .play(), .currentProgress, .play(fromFrame:toFrame:).
  • Android — lottie-android (LottieAnimationView / Compose LottieAnimation): setMinAndMaxFrame, progress.
  • React Native — lottie-react-native (<LottieView source={...} progress={anim} />, controle progress com Animated).

O mesmo .lottie/.json funciona em todas as plataformas; segmentos e conceitos de progresso correspondem à API web.

Otimização

  • Envie .lottie (compactado) em vez de .json bruto; carregue sob demanda players fora da tela e pause quando não estiver visível (IntersectionObserver → play/pause).
  • Prefira o renderizador canvas/WASM dotLottie para muitas animações simultâneas; o renderizador SVG (lottie-web) é adequado para um ícone nítido, mas custa mais DOM para arquivos complexos.
  • Mantenha as composições AE pequenas: menos camadas/keyframes, sem rasters embutidos grandes; achate pré-composições quando possível. O tamanho do arquivo acompanha a complexidade de keyframes e caminhos, não a duração.
  • Recolorir em tempo de execução (temas) em vez de exportar um arquivo por marca/tema.

Entregar e verificar (HTML standalone)

Helper empacotado (scripts/): scripts/seek-shot.sh anim.html 0 1.5 3 congela o harness ?t=N e captura cada momento; scripts/contact-sheet.sh sheet.png frame-*.png os agrupa em uma folha para revisão rápida. Veja scripts/README.md.

Para uma demonstração Lottie autossuficiente (ilustração em loop, ícone animado, estado vazio) a entrega é um arquivo HTML que abre diretamente no navegador — o runtime dotLottie/lottie-web da CDN, um <canvas> e seu .lottie/.json (um arquivo relativo ou uma URL de dados). Sem etapa de build. Um arquivo é o nível certo para enviar um player; não recorra a um bundler.

Contrato de saída:

  • Um arquivo .html: o runtime via CDN (@lottiefiles/dotlottie-web), o canvas e autoplay:false para que o frame seja seu para controlar.
  • Inclua o seek harness para que qualquer frame possa ser congelado para uma captura de tela.

Seek harness — congele um frame exato. ?t=N pula para um frame e o mantém para que uma captura de tela atinja um frame parado e determinístico. O playhead do Lottie está em frames, então pare no frame diretamente:

<script>
  const dl = new DotLottie({ canvas, src: "/icon.lottie", autoplay: false });
  dl.addEventListener("load", () => {
    const t = new URLSearchParams(location.search).get("t");
    if (t !== null) dl.setFrame(parseFloat(t));      // congela no frame N (lottie-web: anim.goToAndStop(N, true))
    else dl.play();
    console.log("totalFrames", dl.totalFrames);       // leia para o frame final
    window.__ready = true;
  });
</script>

Loop de verificação — renderizar → congelar → capturar tela → verificar: abra o arquivo no primeiro / meio / último frame (?t=0, ?t=<total/2>, ?t=<total-1>; leia totalFrames do console), capture cada um e verifique fidelidade (cores/tema corretos, loops de segmento onde pretendido) mais artefatos (canvas borrado por falta de autoResize/DPR, composição cortada, FOUC antes do arquivo carregar, travamentos). Qualquer ferramenta headless funciona:

npx playwright screenshot --wait-for-timeout=600 "file://$PWD/lottie.html?t=42" frame-mid.png

Antes de finalizar:

  1. Abre standalone — sem erros no console, runtime da CDN e o .lottie/.json carregam.
  2. ?t=N (setFrame/goToAndStop) congela o frame correto e determinístico.
  3. Capturas de tela no primeiro / meio / último frame — corresponde ao briefing, nítido, sem cortes.
  4. prefers-reduced-motion respeitado — não faça autoplay de um loop; mostre um frame estático ou ofereça um controle de reprodução.
  5. Easing é intencional — velocidade/segmento de reprodução escolhido de propósito, movimento incorporado no AE lê como projetado.

Referência rápida

ObjetivoChamada
Reproduzir um intervalosetSegment(inicio, fim)
Pular para um framesetFrame(n)
Inverter / balançar`setMode("reverse"
Controlar por scrollautoplay:false + setFrame(p*totalFrames)
Trocar temasetTheme("dark")
Saber duraçãototalFrames após evento load
Interatividade declarativa@lottiefiles/lottie-interactivity

Arquivos de referência

  • references/integration-and-export.md — configuração completa dotLottie-web + React e controle de eventos/segmentos, configurações de modo lottie-interactivity, padrões de scroll/cursor, detalhes de tematização em tempo de execução e a lista de verificação completa de exportação After Effects → Bodymovin com a lista de recursos AE não suportados e como contorná-los.

Individual skills in this repo

This repo contains 13 individual skills — each has its own dedicated page.

nehakanjamala/personal_website

This skill should be used when the user asks to "fix janky CSS animation", "make animation 60fps", "stop layout thrashing", "animate width/height/top/left smoothly", "convert animation to transform", "animate box-shadow performantly", "animate height auto", "FLIP animation", or "why is my scroll/hover animation choppy".

nehakanjamala/personal_website

This skill should be used when the user asks to "respect prefers-reduced-motion", "honor reduced motion", "make my animations accessible", "fix vestibular / motion-sickness issues", "add a useReducedMotion hook", "gate GSAP / Framer Motion / Lenis for reduced motion", or "meet WCAG 2.3.3 / C39". Provides tiered (not all-or-nothing) reduced-motion patterns in CSS and JS.

nehakanjamala/personal_website

Create, modify, debug, and deploy Apify Actors, and write their input and output schemas. Use when building an Actor from scratch, changing or troubleshooting Actor code, generating or updating .actor schema files, or pushing an Actor to the Apify platform. To wrap an existing non-Actor project, use apify-actorization instead.

nehakanjamala/personal_website

Convert existing projects into Apify Actors - serverless cloud programs. Actorize JavaScript/TypeScript (SDK with Actor.init/exit), Python (async context manager), or any language (CLI wrapper). Use when migrating code to Apify, wrapping CLI tools as Actors, or adding Actor SDK to existing projects.

nehakanjamala/personal_website

Deprecated. Output schema generation moved to the apify-actor-development skill; prefer that skill whenever it is available.

nehakanjamala/personal_website

Design and build an official Apify integration for a company's product - workflow-automation apps (Zapier/n8n-style), AI agent plugins (coding-agent skills+MCP bundles or OpenClaw/Hermes-style harnesses), AI framework packages (LangChain/LlamaIndex-style), or direct application clients via apify-client. Use when planning, creating, or reviewing an integration that exposes Apify Actors, runs, datasets, or key-value stores inside another product.

nehakanjamala/personal_website

Universal AI-powered web scraper for any platform. Scrape data from Instagram, Facebook, TikTok, YouTube, LinkedIn, X/Twitter, Google Maps, Google Search, Google Trends, Reddit, Airbnb, Yelp, and 15+ more platforms. Use for lead generation, brand monitoring, competitor analysis, influencer discovery, trend research, content analytics, audience analysis, review analysis, SEO intelligence, recruitment, or any data extraction task.

nehakanjamala/personal_website

This skill should be used when the user asks to "add a glassmorphism effect", "frosted glass UI", "Apple liquid glass style", "frosted blur card", "translucent glass panel animation", "make a frosted nav bar", "build a glass modal/dialog", "animate a glass card on hover", or "add a refracting liquid-glass hero". Covers frosted translucent panels with backdrop-filter blur, edge/specular highlights, SVG liquid-glass refraction, motion on hover/scroll/enter, and accessible reduced-transparency fallbacks.

nehakanjamala/personal_website

This skill should be used when the user asks to "build a scroll animation", "add ScrollTrigger", "pin a section while scrolling", "scrub an animation to scroll", "create a hero timeline", "do a horizontal scroll section", "split text and animate words", "animate a layout change with GSAP Flip", "sync ScrollTrigger with Lenis", "Lenis smooth scroll jittery", "ScrollTrigger markers drift", "ScrollTrigger pins break with Lenis/Locomotive", or "set up smooth scroll with GSAP pinning". Covers GSAP timelines, ScrollTrigger, SplitText, Flip, and Lenis/Locomotive smooth-scroll sync for code-driven web motion.

nehakanjamala/personal_website

This skill should be used when the user asks to "add a hover/press effect", "animate a toggle or switch", "build an animated like button", "make a toast/snackbar slide in", "animate a drawer or modal", "animate list reordering or add/remove", "do a shared-element layout transition", or "polish UI feedback". Covers UI motion with Framer Motion (motion/react) and modern CSS.

nehakanjamala/personal_website

This skill should be used when the user asks to "animate page or route transitions", "add a page transition or crossfade between views", "animate route changes in Next.js App Router", "use the View Transitions API", "AnimatePresence exit doesn't fire on navigation", or "Framer Motion exit animation not working / exit animation before unmount in Next.js". Covers enter/exit page-transition animation with the View Transitions API and Framer Motion, for Next.js App Router and general SPA routing.

nehakanjamala/personal_website

Scrape web pages using Scrapling with anti-bot bypass (like Cloudflare Turnstile), stealth headless browsing, spiders framework, adaptive scraping, and JavaScript rendering. Use when asked to scrape, crawl, or extract data from websites; web_fetch fails; the site has anti-bot protections; write Python code to scrape/crawl; or write spiders.

nehakanjamala/personal_website

This skill should be used when the user asks to "animate an SVG", "make a line draw itself on", "do a stroke draw-on / signature animation", "morph one shape into another", "move an element along a path", "animate an icon/logo", or "animate an SVG gradient or filter". Covers stroke-dashoffset draw-on, path morphing, motion-along-path, and animated icons/gradients/filters via CSS, SMIL, and GSAP.

Habilidades Relacionadas