Communitygithub.com

kschiavo-beep/claude-skills

在網頁與 React 應用程式中,渲染 After Effects 動畫。在實作 Lottie 動畫、JSON 向量動畫、互動式動態圖示、微互動或載入動畫時使用此技能。當任務涉及 Lottie、lottie-web、lottie-react、dotLottie、After Effects JSON 匯出、bodymovin、動畫 SVG 替代方案或設計師建立的動畫時會觸發。可與 GSAP ScrollTrigger 和 Framer Motion 互補,用於滾動驅動和互動式動畫。

claude-skills 是什麼?

這個技能提供了一個完整的指南,幫助開發者在網頁和 React 應用程式中使用 Lottie 技術。Lottie 是由 Airbnb 建立的函式庫,能即時渲染 After Effects 動畫,支援網頁、iOS、Android 和 React Native。它讓設計師能像輸出靜態素材一樣輕鬆地交付動畫,動畫從 After Effects 透過 Bodymovin 外掛程式匯出為 JSON 檔案,再以極低的效能開銷原生渲染。此技能詳細介紹了兩種主要的 Lottie 格式:原始 JSON 和現代壓縮的 .lottie 格式,並涵蓋了多種函式庫選項,如 lottie-web、@lottiefiles/dotlottie-web 及其 React、Vue、Svelte 等框架的整合。內容包含豐富的實作範例,從基本的 HTML 嵌入到 React 中的控制器、事件監聽、滾動驅動動畫、懸停觸發片段播放,以及多動畫與主題支援。此外,也探討了與 GSAP ScrollTrigger 和 Framer Motion 的整合模式,以及針對效能最佳化的技巧,包括檔案壓縮、延遲載入、渲染器選擇和 Web Worker 的使用。

相容平台✓Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/kschiavo-beep/claude-skills/tree/HEAD/.claude/skills/lottie-animations

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Lottie 動畫

總覽

Lottie 是一個函式庫,用於在網頁、iOS、Android 和 React Native 上即時渲染 After Effects 動畫。由 Airbnb 建立,它讓設計師能像傳遞靜態素材一樣輕鬆地交付動畫。動畫從 After Effects 使用 Bodymovin 外掛程式匯出為 JSON 檔案,然後以極低的效能開銷在原生環境中渲染。

何時使用 Lottie:

  • 需要像素級完美保真度的設計師創作動畫
  • 複雜的動態圖示與微互動
  • 載入動畫與進度指示器
  • 引導流程與教學動畫
  • 行銷動畫與促銷內容
  • 替代 GIF/影片,具有較小的檔案大小與可擴展性

主要優勢:

  • 基於向量(可擴展,品質不損失)
  • 檔案大小明顯小於 GIF 或影片
  • 可在執行時編輯(顏色、速度、片段)
  • 透過 After Effects 獲得完整的設計師控制
  • 跨平台渲染一致性
  • 互動式控制(播放、暫停、搜尋、循環)

核心概念

Lottie 格式類型

1. JSON Lottie (.json)

  • 原始的 Lottie 格式
  • 從 After Effects 透過 Bodymovin 外掛程式匯出
  • 人類可讀的 JSON 結構
  • 較大的檔案大小(未壓縮)
  • 在所有平台上廣泛支援

2. dotLottie (.lottie)

  • 現代壓縮格式
  • 包含 JSON + 資產的 ZIP 壓縮檔
  • 支援單一檔案中的多個動畫與主題
  • 較小的檔案大小(最多減少 90%)
  • 建議用於生產環境

函式庫選項

lottie-web(原始函式庫):

import lottie from 'lottie-web';

lottie.loadAnimation({
  container: document.getElementById('lottie-container'),
  renderer: 'svg', // 或 'canvas'、'html'
  loop: true,
  autoplay: true,
  path: 'animation.json' // 或 animationData: jsonData
});

@lottiefiles/dotlottie-web(現代,建議使用):

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

new DotLottie({
  canvas: document.getElementById('canvas'),
  src: 'animation.lottie',
  autoplay: true,
  loop: true
});

@lottiefiles/dotlottie-react(React 整合):

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

<DotLottieReact
  src="animation.lottie"
  loop
  autoplay
  style={{ height: 300 }}
/>

lottie-react(替代的 React 包裝器):

import Lottie from 'lottie-react';
import animationData from './animation.json';

<Lottie animationData={animationData} loop={true} />

動畫資料來源

1. LottieFiles (lottie.host)

  • 超過 100,000 個免費動畫
  • 直接 URL 嵌入
  • CDN 託管

2. 本機 JSON/dotLottie 檔案

  • 與應用程式一起打包
  • 更好的效能(無網路請求)
  • 對版本控制友好

3. After Effects 匯出

  • 自訂設計師動畫
  • 需要 Bodymovin 外掛程式
  • 匯出設定對檔案大小至關重要

常見模式

1. 使用 dotLottie-web 的基礎 HTML 整合

<!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. 帶有控制器的 React 元件

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}>播放</button>
        <button onClick={handlePause}>暫停</button>
        <button onClick={handleStop}>停止</button>
        <button onClick={() => handleSeek(30)}>搜尋到影格 30</button>
      </div>
    </div>
  );
};

3. 事件監聽器與生命週期鉤子

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('動畫已載入');
    const onPlay = () => console.log('動畫已開始');
    const onPause = () => console.log('動畫已暫停');
    const onComplete = () => console.log('動畫已完成');
    const onFrame = ({ currentFrame }) => console.log('影格:', 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. 使用 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. 懸停觸發的片段播放

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. 多動畫與主題支援

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(DotLottieWorker)

import { DotLottieWorker } from '@lottiefiles/dotlottie-web';

// 將動畫渲染卸載到 Web Worker
new DotLottieWorker({
  canvas: document.getElementById('canvas'),
  src: 'heavy-animation.lottie',
  autoplay: true,
  loop: true,
  workerId: 'worker-1' // 按 worker 分組多個動畫
});

// 在獨立的 worker 中執行多個動畫
new DotLottieWorker({
  canvas: document.getElementById('canvas-2'),
  src: 'animation-2.lottie',
  autoplay: true,
  loop: true,
  workerId: 'worker-2'
});

整合模式

與 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;

    // 將 Lottie 與滾動同步
    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>
  );
};

與 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>
  );
};

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>

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}>播放</button>

效能最佳化

檔案大小最佳化

1. After Effects 中的匯出設定:

  • 啟用「Skip images that aren't used」
  • 盡可能使用「Glyphs」而非字型
  • 簡化路徑(在 illustrator 中減少點數)
  • 避免產生大量資料的效果(粒子、雜訊)
  • 使用形狀圖層而非向量圖層

2. 壓縮:

  • 使用 dotLottie 格式 (.lottie) 進行自動壓縮
  • 執行 JSON 通過 Lottie 最佳化工具
  • 移除不必要的後設資料

3. 延遲載入:

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>
  );
};

執行時期效能

1. 渲染器選擇:

// SVG:最佳品質,複雜動畫較慢
// Canvas:效能較好,光柵化
// HTML:支援有限,僅用於簡單動畫

// 對於複雜動畫,偏好 Canvas
new DotLottie({
  canvas: document.getElementById('canvas'),
  src: 'animation.lottie',
  autoplay: true,
  loop: true,
  renderConfig: {
    devicePixelRatio: window.devicePixelRatio || 1
  }
});

2. Web Workers:

// 將沉重動畫卸載到 worker
import { DotLottieWorker } from '@lottiefiles/dotlottie-web';

new DotLottieWorker({
  canvas: document.getElementById('canvas'),
  src: 'heavy-animation.lottie',
  autoplay: true,
  loop: true
});

3. 行動裝置最佳化:

// 在行動裝置上降低品質
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
  }
});

常見陷阱

1. 因清理不當導致的記憶體洩漏

問題: 元件卸載時未銷毀 Lottie 實例。

解決方案:

const SafeAnimation = () => {
  const [dotLottie, setDotLottie] = React.useState(null);

  React.useEffect(() => {
    // 當元件卸載時清理
    return () => {
      if (dotLottie) {
        dotLottie.destroy();
      }
    };
  }, [dotLottie]);

  return (
    <DotLottieReact
      src="animation.lottie"
      loop
      autoplay
      dotLottieRefCallback={setDotLottie}
    />
  );
};

2. 檔案大小過大

問題: 未經最佳化的動畫會導致下載時間延長和效能問題。

解決方案:

  • 使用 dotLottie 格式進行壓縮
  • 在匯出時簡化動畫
  • 實作延遲載入
  • 使用 CDN 進行快取

3. 遺漏的渲染器設定

問題: 在 HiDPI 螢幕上出現模糊或畫質不佳。

解決方案:

// 設定 devicePixelRatio 以獲得清晰渲染
new DotLottie({
  canvas: document.getElementById('canvas'),
  src: 'animation.lottie',
  autoplay: true,
  loop: true,
  renderConfig: {
    devicePixelRatio: window.devicePixelRatio || 1
  }
});

4. 不正確的跨平台測試

問題: 在不同瀏覽器或裝置上渲染結果不同。

解決方案:

  • 在所有目標瀏覽器上測試
  • 使用多方填充或替代方案處理不受支援的功能
  • 針對行動裝置調整品質設定

5. 互動性實作不當

問題: 控制的動畫行為與預期不符。

解決方案:

  • 正確使用 play、pause、stop 和 seek 方法
  • 正確設定事件監聽器以觸發特定動作
  • 在適當的時機(如使用者互動後)初始化動畫

6. 忽視無障礙性

問題: 使用者如果偏好減少動畫,可能會感到不適。

解決方案:

  • 遵守 prefers-reduced-motion 媒體查詢
  • 為重要內容提供靜態替代方案
  • 允許使用者暫停或停止動畫

最佳實務

1. 使用 Canvas 渲染器以獲得最佳效能

// Canvas 適用於複雜或長時間運行的動畫
// SVG 適用於需要互動性或可縮放性的簡單動畫
new DotLottie({
  canvas: document.getElementById('canvas'),
  src: 'animation.lottie',
  autoplay: true,
  loop: true
});

2. 實作延遲載入以改善初始載入時間

const LazyLoadedLottie = () => {
  const observerRef = React.useRef(null);
  const [visible, setVisible] = React.useState(false);

  React.useEffect(() => {
    observerRef.current = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) {
        setVisible(true);
        observerRef.current?.disconnect();
      }
    });

    if (observerRef.current) {
      observerRef.current.observe(document.getElementById('lottie-container'));
    }

    return () => observerRef.current?.disconnect();
  }, []);

  return (
    <div id="lottie-container">
      {visible && (
        <DotLottieReact src="animation.lottie" loop autoplay />
      )}
    </div>
  );
};

3. 正確的事件處理與清理

// 始終在元件卸載時移除事件監聽器
useEffect(() => {
  const handleEvent = () => {};
  dotLottie?.addEventListener('play', handleEvent);
  return () => dotLottie?.removeEventListener('play', handleEvent);
}, [dotLottie]);

4. 具響應性的動畫大小調整

const ResponsiveLottie = () => {
  const containerRef = React.useRef(null);
  const [dimensions, setDimensions] = React.useState({ width: 0, height: 0 });

  React.useEffect(() => {
    const updateDimensions = () => {
      if (containerRef.current) {
        setDimensions({
          width: containerRef.current.offsetWidth,
          height: containerRef.current.offsetHeight
        });
      }
    };

    updateDimensions();
    window.addEventListener('resize', updateDimensions);
    return () => window.removeEventListener('resize', updateDimensions);
  }, []);

  return (
    <div ref={containerRef} style={{ width: '100%', height: '100%' }}>
      <DotLottieReact
        src="animation.lottie"
        style={{ width: dimensions.width, height: dimensions.height }}
        loop
        autoplay
      />
    </div>
  );
};

5. 遵守使用者偏好設定

const AccessibleLottie = ({ src, children }) => {
  const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  if (prefersReducedMotion) {
    return <StaticContent>{children}</StaticContent>;
  }

  return (
    <DotLottieReact
      src={src}
      loop
      autoplay
    />
  );
};

6. 監控與記錄

// 追蹤關鍵事件以進行除錯
const traceLottieEvents = (instance) => {
  instance.addEventListener('load', () => console.log('Lottie 載入'));
  instance.addEventListener('ready', () => console.log('Lottie 就緒'));
  instance.addEventListener('play', () => console.log('Lottie 播放'));
  instance.addEventListener('pause', () => console.log('Lottie 暫停'));
  instance.addEventListener('complete', () => console.log('Lottie 完成'));
  instance.addEventListener('error', (error) => console.error('Lottie 錯誤', error));
};

進階用法

動態顏色覆蓋

Lottie 允許在執行時期動態更改顏色:

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

new DotLottie({
  canvas: document.getElementById('canvas'),
  src: 'animation.lottie',
  autoplay: true,
  loop: true,
  // 動態覆蓋顏色
  assets: [{
    id: 'color1',
    color: '#FF0000'
  }]
});

自訂動作與播放模式

dotLottie 格式支援 PlayMode 和 Theme 等進階功能:

new DotLottie({
  canvas: document.getElementById('canvas'),
  src: 'animation.lottie',
  autoplay: true,
  loop: true
});

與其他動畫函式庫整合

Lottie 可以與其他動畫函式庫無縫整合:

  • GSAP:用於時間軸控制
  • Framer Motion:用於 React 動畫
  • Anime.js:用於輕量級動畫
  • Three.js:用於 3D 動畫

如需更多範例與文件,請參閱:

Individual skills in this repo

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

相關技能