dotlottie-web
Guides AI agents in implementing Lottie animations using dotLottie runtimes, covering package selection, installation, and basic usage for web projects in vanilla JavaScript, React, and Next.js.
About this skill
This AI agent skill serves as a comprehensive guide for implementing Lottie and dotLottie animations across various web projects. It equips an AI agent with the knowledge to make informed decisions regarding package selection between `@lottiefiles/dotlottie-web` for direct canvas control and maximum performance in framework-agnostic contexts, and `@lottiefiles/dotlottie-react` for seamless integration into React applications. The skill provides clear instructions for installation and showcases basic implementation patterns for both vanilla JavaScript and React. Beyond basic setup, this skill offers guidance on crucial aspects such as leveraging Web Workers for improved performance, managing animation states, applying themes, and dynamically overriding animation slots. It also covers performance best practices and common animation patterns, ensuring that the generated code is not only functional but also efficient and maintainable. This makes it an invaluable resource for agents tasked with building, debugging, or optimizing Lottie animations. Developers would use this skill through an AI agent to quickly scaffold animation code, troubleshoot existing implementations, or explore advanced animation features. It ensures consistency and adherence to best practices, saving time and reducing potential errors in complex animation setups.
Best use case
The primary use case is assisting web developers in efficiently integrating and managing Lottie animations within their projects. AI agents leveraging this skill can generate correct, optimized, and framework-specific code for Lottie animations, making it especially beneficial for developers working with rich UI/UX involving motion graphics, or those needing to quickly prototype animation features.
Guides AI agents in implementing Lottie animations using dotLottie runtimes, covering package selection, installation, and basic usage for web projects in vanilla JavaScript, React, and Next.js.
The user should expect well-structured, functional, and optimized code snippets or complete implementations for Lottie and dotLottie animations, tailored to their specified web project environment.
Practical example
Example input
Draft a React component that displays a dotLottie animation from `public/hero.lottie`. It should autoplay and loop. Advise on the best package and provide the installation command.
Example output
```typescript
npm install @lottiefiles/dotlottie-react
import { DotLottieReact } from '@lottiefiles/dotlottie-react';
function HeroAnimation() {
return (
<DotLottieReact
src="/hero.lottie"
autoplay
loop
style={{ width: '100%', height: 'auto' }}
/>
);
}
export default HeroAnimation;
```When to use this skill
- Implementing new Lottie or dotLottie animations in vanilla JS, React, or Next.js web projects.
- Debugging or optimizing existing Lottie animation code for performance and correctness.
- When needing to select the most appropriate Lottie runtime package based on project requirements.
- Exploring advanced Lottie features like theming, dynamic slots, or Web Worker integration.
When not to use this skill
- For animation tasks that do not involve Lottie or dotLottie formats.
- In non-web development contexts (e.g., native mobile apps, desktop applications).
- When working with entirely different animation libraries or frameworks (e.g., pure CSS animations, GSAP for non-Lottie assets).
How dotlottie-web Compares
| Feature / Agent | dotlottie-web | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | easy | N/A |
Frequently Asked Questions
What does this skill do?
Guides AI agents in implementing Lottie animations using dotLottie runtimes, covering package selection, installation, and basic usage for web projects in vanilla JavaScript, React, and Next.js.
How difficult is it to install?
The installation complexity is rated as easy. You can find the installation instructions above.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Cursor vs Codex for AI Workflows
Compare Cursor and Codex for AI coding workflows, repository assistance, debugging, refactoring, and reusable developer skills.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
SKILL.md Source
# dotLottie Implementation Guidelines
You are an expert at implementing Lottie animations using dotLottie runtimes. Follow these guidelines when working with dotLottie in web projects.
## Package Selection
### Use `@lottiefiles/dotlottie-web` when:
* You need direct canvas control
* Building framework-agnostic code
* Maximum performance is critical
* You want the smallest bundle
### Use `@lottiefiles/dotlottie-react` when:
* Building React applications
* You want declarative component API
* You need React lifecycle integration
## Installation
```bash
# Web (vanilla JS, Vue, Svelte, etc.)
npm install @lottiefiles/dotlottie-web
# React
npm install @lottiefiles/dotlottie-react
```
## Basic Implementation
### Vanilla JavaScript
```typescript
import { DotLottie } from '@lottiefiles/dotlottie-web';
const dotLottie = new DotLottie({
canvas: document.getElementById('canvas') as HTMLCanvasElement,
src: 'https://example.com/animation.lottie',
autoplay: true,
loop: true,
});
```
### React
```tsx
import { DotLottieReact } from '@lottiefiles/dotlottie-react';
function Animation() {
return (
<DotLottieReact
src="https://example.com/animation.lottie"
autoplay
loop
/>
);
}
```
### React with Instance Control
```tsx
import { useRef } from 'react';
import { DotLottieReact } from '@lottiefiles/dotlottie-react';
import type { DotLottie } from '@lottiefiles/dotlottie-web';
function Animation() {
const dotLottieRef = useRef<DotLottie | null>(null);
return (
<DotLottieReact
src="https://example.com/animation.lottie"
dotLottieRefCallback={(dotLottie) => (dotLottieRef.current = dotLottie)}
/>
);
}
```
## .lottie vs .json
**Always prefer `.lottie` format over `.json`:**
* Smaller file size (compressed)
* Supports multiple animations in one file
* Embedded assets (images, fonts)
* State machines for interactivity
* Theming with slots
## Web Workers (Recommended for Performance)
Use `DotLottieWorker` to offload animation rendering to a Web Worker, keeping the main thread free for UI interactions:
### Basic Worker Usage
```typescript
import { DotLottieWorker } from '@lottiefiles/dotlottie-web';
const dotLottie = new DotLottieWorker({
canvas: document.getElementById('canvas') as HTMLCanvasElement,
src: 'https://example.com/animation.lottie',
autoplay: true,
loop: true,
});
```
### Worker Grouping (Multiple Animations)
By default, all `DotLottieWorker` instances share the same worker. Group animations into separate workers using `workerId`:
```typescript
// Hero animation in its own worker
const heroAnimation = new DotLottieWorker({
canvas: heroCanvas,
src: 'hero.lottie',
workerId: 'hero-worker',
});
// UI animations share a different worker
const buttonAnimation = new DotLottieWorker({
canvas: buttonCanvas,
src: 'button.lottie',
workerId: 'ui-worker',
});
```
### When to Use Workers
* **Use `DotLottieWorker`** for:
* Multiple simultaneous animations
* Complex animations with many layers
* Animations running alongside heavy JS operations
* Mobile devices where main thread performance is critical
* **Use regular `DotLottie`** for:
* Single simple animations
* When you need synchronous frame access
* SSR environments (workers not available)
### React with Workers
```tsx
import { DotLottieWorkerReact } from '@lottiefiles/dotlottie-react';
function Animation() {
return (
<DotLottieWorkerReact
src="animation.lottie"
autoplay
loop
workerId="my-worker" // Optional: dedicate to specific worker
/>
);
}
```
## State Machines (Interactivity)
State machines enable interactive animations without code. See the [State Machine Guide](https://github.com/LottieFiles/dotlottie-web/wiki/dotLottie-State-Machine-Guide) for details.
```typescript
const dotLottie = new DotLottie({
canvas,
src: 'interactive.lottie', // Contains state machine
autoplay: true,
});
// Fire events to trigger state transitions
dotLottie.stateMachineFireEvent('click');
dotLottie.stateMachineFireEvent('hover');
dotLottie.stateMachineFireEvent('custom-event');
// Set numeric/boolean/string inputs for state conditions
// See: https://github.com/LottieFiles/dotlottie-web/wiki/dotLottie-State-Machine-Guide#working-with-inputs
dotLottie.stateMachineSetNumericInput('progress', 0.5);
dotLottie.stateMachineSetBooleanInput('isActive', true);
dotLottie.stateMachineSetStringInput('mode', 'dark');
```
### State Machine Events
* `click` - User click/tap
* `hover` - Mouse enter
* `unhover` - Mouse leave
* `complete` - Animation finished
* Custom events defined in the state machine
## Theming with Slots
Slots allow runtime color/value customization. Themes follow the [dotLottie 2.0 spec](https://dotlottie.io/spec/2.0/#themes).
```typescript
const dotLottie = new DotLottie({
canvas,
src: 'themed.lottie',
themeId: 'dark-mode', // Use embedded theme by ID
});
// Or apply theme data directly (JSON string per dotLottie 2.0 spec)
// See: https://dotlottie.io/spec/2.0/#themes
dotLottie.setThemeData(JSON.stringify({
rules: [
{ id: 'primary-color', value: [1, 0.34, 0.13] }, // RGB values 0-1
]
}));
```
## Dynamic Slot Overriding
Slots enable runtime customization of animated properties using typed APIs.
Available slot types: color, scalar, vector, gradient, text, image.
Key APIs: `getSlotIds()`, `getSlotType()`, `setColorSlot()`, `setScalarSlot()`,
`setVectorSlot()`, `setGradientSlot()`, `setTextSlot()`, `resetSlot()`, `clearSlots()`.
For complete API reference with code examples for each slot type, animated keyframes,
resetting, bulk updates, common use cases (branding, dark mode, progress indicators),
and React integration, see [Dynamic Slots Reference](references/dynamic-slots.md).
## Markers & Segments
### Playing Specific Segments
```typescript
// Play frames 0-60
dotLottie.setSegment(0, 60);
dotLottie.play();
// Play by marker name (defined in animation)
dotLottie.setMarker('intro');
dotLottie.play();
```
### Getting Markers
```typescript
const markers = dotLottie.markers();
// Returns: [{ name: 'intro', time: 0, duration: 60 }, ...]
```
## Event Handling
```typescript
dotLottie.addEventListener('load', () => {
console.log('Animation loaded');
});
dotLottie.addEventListener('play', () => {
console.log('Playing');
});
dotLottie.addEventListener('complete', () => {
console.log('Animation completed');
});
dotLottie.addEventListener('frame', ({ currentFrame }) => {
console.log('Frame:', currentFrame);
});
// Clean up
dotLottie.removeEventListener('load', handler);
```
## Performance Best Practices
### 1. Use Web Workers for Complex Animations
```typescript
import { DotLottieWorker } from '@lottiefiles/dotlottie-web';
// Offload rendering to worker thread
const dotLottie = new DotLottieWorker({
canvas,
src: 'complex-animation.lottie',
});
```
### 2. Lazy Load Animations
```typescript
// Only load when visible
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
loadAnimation();
observer.disconnect();
}
});
});
observer.observe(container);
```
### 3. Auto-Freeze is Enabled by Default
DotLottie automatically freezes animations when they're not visible (offscreen). To disable this behavior:
```typescript
const dotLottie = new DotLottie({
canvas,
src: 'animation.lottie',
renderConfig: {
freezeOnOffscreen: false, // Disable auto-freeze (not recommended)
},
});
```
### 4. Device Pixel Ratio
By default, devicePixelRatio is set to 75% of the actual value for better performance. For full retina quality (with higher performance cost):
```typescript
const dotLottie = new DotLottie({
canvas,
src: 'animation.lottie',
renderConfig: {
devicePixelRatio: window.devicePixelRatio, // Full retina (higher CPU/GPU)
},
});
```
### 5. Clean Up (Vanilla JS only)
```typescript
// Always destroy when done (vanilla JS)
dotLottie.destroy();
```
**Note:** `DotLottieReact` handles cleanup automatically on unmount - no manual cleanup needed.
### 6. Frame Interpolation Control
```typescript
const dotLottie = new DotLottie({
canvas,
src: 'animation.lottie',
useFrameInterpolation: true, // Smooth playback (default)
// useFrameInterpolation: false, // Match original AE frame rate
});
```
## Multi-Animation Files
A single `.lottie` file can contain multiple animations:
```typescript
// Load specific animation by ID
dotLottie.loadAnimation('animation-2');
// Get all animation IDs
const animations = dotLottie.manifest?.animations;
// Returns: [{ id: 'animation-1' }, { id: 'animation-2' }]
```
## Canvas Sizing
**Set canvas size via CSS styles** (recommended). DotLottie will automatically determine the optimal drawing area:
```html
<canvas id="canvas" style="width: 400px; height: 400px;"></canvas>
```
### Auto-Resize to Container
Use the `autoResize` render config to automatically resize when the container changes:
```typescript
const dotLottie = new DotLottie({
canvas,
src: 'animation.lottie',
renderConfig: {
autoResize: true, // Canvas resizes to fit container
},
});
```
## Common Patterns
### Play on Hover
```typescript
canvas.addEventListener('mouseenter', () => dotLottie.play());
canvas.addEventListener('mouseleave', () => dotLottie.pause());
```
### Play on Click (Once)
```typescript
canvas.addEventListener('click', () => {
dotLottie.setFrame(0);
dotLottie.setLoop(false);
dotLottie.play();
});
```
### Scrub with Scroll
```typescript
window.addEventListener('scroll', () => {
const progress = window.scrollY / (document.body.scrollHeight - window.innerHeight);
const frame = progress * dotLottie.totalFrames;
dotLottie.setFrame(frame);
});
```
### Loading States (React)
```tsx
function Animation() {
const [isLoaded, setIsLoaded] = useState(false);
return (
<>
{!isLoaded && <Skeleton />}
<DotLottieReact
src="animation.lottie"
style={{ opacity: isLoaded ? 1 : 0 }}
dotLottieRefCallback={(dotLottie) => {
dotLottie.addEventListener('load', () => setIsLoaded(true));
}}
/>
</>
);
}
```
### Responsive Animation
```tsx
function ResponsiveAnimation() {
return (
<DotLottieReact
src="animation.lottie"
autoplay
loop
style={{ width: '100%', maxWidth: '400px' }}
renderConfig={{ autoResize: true }}
/>
);
}
```
## Debugging
```typescript
// Check if loaded
console.log('Loaded:', dotLottie.isLoaded);
// Get animation info
console.log('Duration:', dotLottie.duration);
console.log('Total Frames:', dotLottie.totalFrames);
console.log('Current Frame:', dotLottie.currentFrame);
console.log('Is Playing:', dotLottie.isPlaying);
console.log('Loop:', dotLottie.loop);
console.log('Speed:', dotLottie.speed);
// Get manifest (for .lottie files)
console.log('Manifest:', dotLottie.manifest);
```
## Error Handling
```typescript
dotLottie.addEventListener('loadError', (error) => {
console.error('Failed to load animation:', error);
// Show fallback UI
});
```
## SSR / Next.js Considerations
dotLottie requires browser APIs. For SSR frameworks:
```tsx
import dynamic from 'next/dynamic';
const DotLottieReact = dynamic(
() => import('@lottiefiles/dotlottie-react').then(mod => mod.DotLottieReact),
{ ssr: false }
);
function Animation() {
return <DotLottieReact src="animation.lottie" autoplay loop />;
}
```
## Resources
* Documentation: [https://developers.lottiefiles.com/docs/dotlottie-player](https://developers.lottiefiles.com/docs/dotlottie-player)
* State Machine Guide: [https://github.com/LottieFiles/dotlottie-web/wiki/dotLottie-State-Machine-Guide](https://github.com/LottieFiles/dotlottie-web/wiki/dotLottie-State-Machine-Guide)
* GitHub: [https://github.com/LottieFiles/dotlottie-web](https://github.com/LottieFiles/dotlottie-web)
* dotLottie 2.0 Spec: [https://dotlottie.io/spec/2.0/](https://dotlottie.io/spec/2.0/)
* Create .lottie files: [https://lottiefiles.com](https://lottiefiles.com) or [https://creators.lottiefiles.com](https://creators.lottiefiles.com)Related Skills
laravel-expert
Senior Laravel Engineer role for production-grade, maintainable, and idiomatic Laravel solutions. Focuses on clean architecture, security, performance, and modern standards (Laravel 10/11+).
debug-nw
Debug a Nativewind v5 setup issue. Walks through common configuration problems with metro, babel, postcss, and dependencies.
Go Production Engineering
You are a Go production engineering expert. Follow this system for every Go project — from architecture decisions through production deployment. Apply phases sequentially for new projects; use individual phases as needed for existing codebases.
Database Engineering Mastery
> Complete database design, optimization, migration, and operations system. From schema design to production monitoring — covers PostgreSQL, MySQL, SQLite, and general SQL patterns.
afrexai-code-reviewer
Enterprise-grade code review agent. Reviews PRs, diffs, or code files for security vulnerabilities, performance issues, error handling gaps, architecture smells, and test coverage. Works with any language, any repo, no dependencies required.
API Documentation Generator
Generate production-ready API documentation from endpoint descriptions. Outputs OpenAPI 3.0, markdown reference docs, and SDK quickstart guides.
bili-rs
Development skill for bili-rs, a Rust CLI tool for Bilibili (B站). Use when implementing features, fixing bugs, or extending the bilibili-cli-rust codebase. Provides architecture conventions, API endpoints, coding patterns, and project-specific constraints. Triggers on tasks involving adding CLI commands, calling Bilibili APIs, handling authentication, implementing output formatting, or working with the layered cli/commands/client/payloads architecture.
Puppeteer
Automate Chrome and Chromium with Puppeteer for scraping, testing, screenshots, and browser workflows.
pharaoh
Codebase knowledge graph with 23 development workflow skills. Query architecture, dependencies, blast radius, dead code, and test coverage via MCP. Requires GitHub App installation (read-only repo access) and OAuth authentication. Connects to external MCP server at mcp.pharaoh.so.
git-commit-helper
Generate standardized git commit messages following Conventional Commits format. Use this skill when the user asks to commit code, write a commit message, or create a git commit. Enforces team conventions for type prefixes, scope naming, message length, and breaking change documentation.
ask-claude
Delegate a task to Claude Code CLI and immediately report the result back in chat. Supports persistent sessions with full context memory. Safe execution: no data exfiltration, no external calls, file operations confined to workspace. Use when the user asks to run Claude, delegate a coding task, continue a previous Claude session, or any task benefiting from Claude Code's tools (file editing, code analysis, bash, etc.).
bnbchain-mcp
Interact with the BNB Chain Model Context Protocol (MCP) server. Blocks, contracts, tokens, NFTs, wallet, Greenfield, and ERC-8004 agent tools. Use npx @bnb-chain/mcp@latest or read the official skill page.