乐闻世界logo
搜索文章和话题

How to integrate and use Lottie animations in Web projects?

2月19日 17:50

There are multiple ways to use Lottie animations in Web projects. Here are detailed implementation methods:

1. Using lottie-web Library

Installation:

bash
npm install lottie-web # or yarn add lottie-web

Basic Usage:

javascript
import lottie from 'lottie-web'; // Method 1: Load from URL const animation = lottie.loadAnimation({ container: document.getElementById('lottie-container'), renderer: 'svg', // 'svg', 'canvas', 'html' loop: true, autoplay: true, path: 'https://example.com/animation.json' }); // Method 2: Load from local file import animationData from './animation.json'; const animation = lottie.loadAnimation({ container: document.getElementById('lottie-container'), renderer: 'svg', loop: true, autoplay: true, animationData: animationData });

2. Using LottieFiles Player (Recommended)

HTML Method:

html
<script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script> <lottie-player src="https://example.com/animation.json" background="transparent" speed="1" style="width: 300px; height: 300px" loop autoplay> </lottie-player>

React Component Method:

bash
npm install @lottiefiles/react-lottie-player # or yarn add @lottiefiles/react-lottie-player
jsx
import { Player } from '@lottiefiles/react-lottie-player'; function MyComponent() { return ( <Player autoplay loop src="https://example.com/animation.json" style={{ height: '300px', width: '300px' }} /> ); }

3. Using react-lottie

Installation:

bash
npm install react-lottie # or yarn add react-lottie
jsx
import Lottie from 'react-lottie'; import animationData from './animation.json'; const defaultOptions = { loop: true, autoplay: true, animationData: animationData, rendererSettings: { preserveAspectRatio: 'xMidYMid slice' } }; function MyComponent() { return <Lottie options={defaultOptions} height={400} width={400} />; }

4. Animation Control

Playback Control:

javascript
const animation = lottie.loadAnimation({...}); // Play animation.play(); // Pause animation.pause(); // Stop animation.stop(); // Set playback speed animation.setSpeed(1.5); // Set playback direction animation.setDirection(-1); // -1 reverse, 1 forward // Jump to specific frame animation.goToAndStop(30, true); // true for frame number, false for time // Set progress animation.goToAndPlay(0.5, true); // 0.5 means 50% progress

Event Listeners:

javascript
animation.addEventListener('complete', () => { console.log('Animation completed'); }); animation.addEventListener('loopComplete', () => { console.log('Animation loop completed'); }); animation.addEventListener('enterFrame', () => { console.log('Animation entered frame'); }); animation.addEventListener('config_ready', () => { console.log('Configuration ready'); }); animation.addEventListener('data_ready', () => { console.log('Data ready'); }); animation.addEventListener('DOMLoaded', () => { console.log('DOM loaded'); }); animation.addEventListener('destroy', () => { console.log('Animation destroyed'); });

5. Dynamic Property Modification

Modify Colors:

javascript
// Use colorFilters animation.setColorFilter([ { keypath: 'layer1', color: '#FF0000' } ]); // Or directly modify JSON data animationData.layers[0].shapes[0].c.k = [1, 0, 0, 1]; animation.destroy(); const newAnimation = lottie.loadAnimation({ container: document.getElementById('lottie-container'), animationData: animationData, renderer: 'svg', loop: true, autoplay: true });

Modify Text:

javascript
// For text layers animationData.layers.forEach(layer => { if (layer.ty === 1) { // Text layer layer.t.d.k[0].s.t = 'New Text'; } });

6. Performance Optimization

Use Canvas Rendering:

javascript
const animation = lottie.loadAnimation({ container: document.getElementById('lottie-container'), renderer: 'canvas', // Canvas has better performance than SVG loop: true, autoplay: true, path: 'animation.json', rendererSettings: { preserveAspectRatio: 'xMidYMid slice', clearCanvas: false, progressiveLoad: true, hideOnTransparent: true } });

Lazy Loading:

javascript
// Use Intersection Observer const observer = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting) { const animation = lottie.loadAnimation({ container: entry.target, renderer: 'svg', loop: true, autoplay: true, path: 'animation.json' }); observer.unobserve(entry.target); } }); }); document.querySelectorAll('.lottie-lazy').forEach(el => { observer.observe(el); });

7. Responsive Handling

javascript
// Listen to window resize const animation = lottie.loadAnimation({...}); window.addEventListener('resize', () => { animation.resize(); }); // Or use CSS media queries #lottie-container { width: 100%; max-width: 500px; height: auto; } @media (max-width: 768px) { #lottie-container { max-width: 300px; } }

8. Framework Integration

Vue.js:

vue
<template> <div ref="lottieContainer"></div> </template> <script> import lottie from 'lottie-web'; import animationData from './animation.json'; export default { mounted() { this.animation = lottie.loadAnimation({ container: this.$refs.lottieContainer, renderer: 'svg', loop: true, autoplay: true, animationData: animationData }); }, beforeDestroy() { this.animation.destroy(); } }; </script>

Angular:

typescript
import { Component, AfterViewInit, ElementRef, ViewChild } from '@angular/core'; import lottie from 'lottie-web'; import * as animationData from './animation.json'; @Component({ selector: 'app-lottie', template: '<div #lottieContainer></div>' }) export class LottieComponent implements AfterViewInit { @ViewChild('lottieContainer', { static: true }) lottieContainer: ElementRef; ngAfterViewInit() { lottie.loadAnimation({ container: this.lottieContainer.nativeElement, renderer: 'svg', loop: true, autoplay: true, animationData: animationData }); } }

9. Error Handling

javascript
try { const animation = lottie.loadAnimation({ container: document.getElementById('lottie-container'), renderer: 'svg', loop: true, autoplay: true, path: 'animation.json' }); animation.addEventListener('data_failed', (error) => { console.error('Animation data failed to load:', error); // Show fallback content document.getElementById('lottie-container').innerHTML = '<img src="fallback.png" alt="Animation fallback">'; }); } catch (error) { console.error('Failed to load animation:', error); }

10. Best Practices

  • Use CDN to accelerate animation file loading
  • Provide appropriate placeholders for animations
  • Implement fallback solutions (static images or CSS animations)
  • Clean up animation instances when components unmount
  • Use Intersection Observer for lazy loading
  • Choose appropriate renderer based on device performance
  • Compress and optimize JSON file sizes
  • Use Service Worker to cache animation files
标签:Lottie