Lottie 动画
概述
Lottie 是一个用于在 Web、iOS、Android 和 React Native 上实时渲染 After Effects 动画的库。由 Airbnb 创建,它使设计师能够像交付静态资源一样轻松地交付动画。动画通过 Bodymovin 插件从 After Effects 导出为 JSON 文件,然后以最小的性能开销本地渲染。
何时使用 Lottie:
- 需要像素级完美保真度的设计师创建动画
- 复杂的动画图标和微交互
- 加载动画和进度指示器
- 引导序列和教程动画
- 营销动画和推广内容
- 替代 GIF/视频,文件更小且可缩放
主要优势:
- 基于矢量(可缩放而不会损失质量)
- 文件大小明显小于 GIF 或视频
- 运行时可编辑(颜色、速度、片段)
- 通过 After Effects 实现完全的设计师控制
- 跨平台渲染一致性
- 交互控制(播放、暂停、跳转、循环)
核心概念
Lottie 格式类型
1. JSON Lottie (.json)
- 原始 Lottie 格式
- 通过 Bodymovin 插件从 After Effects 导出
- 人类可读的 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 中的导出设置:
- 启用“跳过未使用的图像”
- 尽可能使用“字形”代替字体
- 简化路径(在 illustrator 中减少点数)
- 避免会产生大量数据的特效(粒子、噪点)
- 使用形状图层代替矢量图层
2. 压缩:
- 使用 dotLottie 格式 (.lottie) 进行自动压缩
- 通过 Lottie 优化工具运行 JSON
- 删除不必要的元数据
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"
dotLottieRefCallback={setDotLottie}
/>
);
};
2. 在 hooks 之外访问 Lottie 实例
问题: 在事件回调之外尝试使用 Lottie 实例 API。
解决方案: 始终在 dotLottieRefCallback 内或通过事件监听器访问实例。
3. 忽略错误和加载状态
问题: 假设动画总是成功加载。
解决方案:
const RobustAnimation = () => {
const [error, setError] = React.useState(null);
const [loading, setLoading] = React.useState(true);
const handleError = (err) => {
setError(err);
setLoading(false);
};
const handleLoad = () => {
setLoading(false);
};
if (error) return <div>加载动画时出错</div>;
if (loading) return <div>加载中...</div>;
return (
<DotLottieReact
src="animation.lottie"
onError={handleError}
onLoad={handleLoad}
/>
);
};