lottie動畫指南
效果
概述
本項目使用 svgaplayer.weapp.js
庫來實現 SVGA 動畫播放功能,支持在微信小程序、H5 等多端環境下播放高質量的矢量動畫。SVGA 是一種跨平臺的開源動畫格式,具有文件小、渲染性能高的特點。
技術棧
- 核心庫: svgaplayer.weapp.js (專為小程序優化的 SVGA 播放器)
- 框架: Vue 3 + Composition API
- 平臺: 支持微信小程序、H5 等多端
(svgaplayer.weapp二次封裝)
項目結構
src/
├── components/
│ ├── common/
│ │ └── svgaPlayer.vue # SVGA播放器核心組件
│ └── AnimationTemplate/
│ ├── index.vue # 簡化版動畫模板組件
│ └── AnimationTemplate.vue # 高級動畫模板組件
├── static/
│ └── js/
│ └── svgaplayer.weapp.js # SVGA播放器庫文件
└── pages/└── sale-entry/└── index.vue # 使用示例頁面
核心組件
1. SvgaPlayer 組件 (src/components/common/svgaPlayer.vue
)
這是 SVGA 播放的核心組件,負責加載、解析和播放 SVGA 動畫文件。
主要特性:
- 支持本地和遠程 SVGA 文件加載
- 內置緩存機制,避免重復加載
- 支持循環播放、播放控制
- 提供豐富的回調函數
- 自動適配不同平臺的 Canvas API
2. AnimationTemplate 組件
基于 SvgaPlayer 的封裝組件,提供了更易用的動畫展示模板。
主要特性:
- 全屏遮罩展示
- 支持多種位置布局(居中、頂部、底部)
- 自動播放完成后隱藏
- 支持手動關閉按鈕
使用方法
基礎使用
- 引入組件
<template><view><!-- 基礎使用 --><SvgaPlayerref="svgaPlayerRef":url="animationUrl":width="300":height="300":canvas-id="'myCanvas'":loops="1":clears-after-stop="true"/><!-- 模板組件使用 --><AnimationTemplateref="animationTemplateRef":animation-url="animationUrl":width="400":height="400":loops="1":show-close-button="true"@close="handleAnimationClose"@animationStart="handleAnimationStart"@animationEnd="handleAnimationEnd"/></view>
</template>
<script setup>
import SvgaPlayer from '@/components/common/svgaPlayer.vue';
import AnimationTemplate from '@/components/AnimationTemplate/AnimationTemplate.vue';const svgaPlayerRef = ref(null);
const animationTemplateRef = ref(null);
const animationUrl = 'https://xxx.***.com.cn/frontEnd/files/common/aidfinal1.svga';
</script>
- 程序化控制
// 開始播放動畫
const startAnimation = () => {if (animationTemplateRef.value) {// 設置回調函數setupAnimationCallbacks();// 開始播放animationTemplateRef.value.startAnimation();}
};// 設置動畫回調
const setupAnimationCallbacks = () => {if (animationTemplateRef.value) {// 動畫完成回調animationTemplateRef.value.setOnFinished(() => {console.log('動畫播放完成');animationTemplateRef.value.hide();});// 幀回調animationTemplateRef.value.setOnFrame((frame) => {console.log('當前幀:', frame);});// 進度回調animationTemplateRef.value.setOnPercentage((percentage) => {console.log('播放進度:', Math.round(percentage * 100) + '%');});}
};
API 接口
SvgaPlayer Props
參數 | 類型 | 默認值 | 說明 |
---|---|---|---|
url | String | 必傳 | SVGA 文件的 URL 地址 |
width | String/Number | 300 | 動畫寬度 |
height | String/Number | 300 | 動畫高度 |
canvasId | String | ‘svgaCanvas’ | Canvas 元素的 ID |
loops | Number | 1 | 循環播放次數,0 表示無限循環 |
clearsAfterStop | Boolean | false | 播放完成后是否清除畫布 |
SvgaPlayer Methods
方法名 | 參數 | 說明 |
---|---|---|
initPlayer() | - | 初始化播放器 |
preload(url, callback) | url: 預加載的 URL <br> callback: 回調函數 | 預加載 SVGA 文件 |
showSvga() | - | 顯示并播放動畫 |
startAnimation() | - | 開始播放動畫 |
stopAnimation(clear) | clear: 是否清除畫布 | 停止播放動畫 |
pauseAnimation() | - | 暫停播放動畫 |
setOnFinished(callback) | callback: 回調函數 | 設置播放完成回調 |
setOnFrame(callback) | callback: 回調函數 | 設置幀回調 |
setOnPercentage(callback) | callback: 回調函數 | 設置進度回調 |
AnimationTemplate Props
參數 | 類型 | 默認值 | 說明 |
---|---|---|---|
animationUrl | String | 必傳 | SVGA 文件的 URL 地址 |
width | String/Number | 300 | 動畫寬度 |
height | String/Number | 300 | 動畫高度 |
canvasId | String | ‘animationTemplateCanvas’ | Canvas 元素的 ID |
loops | Number | 1 | 循環播放次數 |
clearsAfterStop | Boolean | false | 播放完成后是否清除畫布 |
showCloseButton | Boolean | true | 是否顯示關閉按鈕 |
backgroundOpacity | Number | 0.5 | 背景遮罩透明度 |
position | String | ‘center’ | 動畫位置:‘center’, ‘top’, ‘bottom’ |
zIndex | Number | 9999 | 層級索引 |
AnimationTemplate Methods
方法名 | 參數 | 說明 |
---|---|---|
show() | - | 顯示動畫 |
hide() | - | 隱藏動畫 |
startAnimation() | - | 開始播放動畫 |
stopAnimation() | - | 停止播放動畫 |
preloadAnimation() | - | 預加載動畫 |
setOnFinished(callback) | callback: 回調函數 | 設置播放完成回調 |
setOnFrame(callback) | callback: 回調函數 | 設置幀回調 |
setOnPercentage(callback) | callback: 回調函數 | 設置進度回調 |
AnimationTemplate Events
事件名 | 參數 | 說明 |
---|---|---|
close | - | 動畫關閉時觸發 |
animationStart | - | 動畫開始播放時觸發 |
animationEnd | - | 動畫播放結束時觸發 |
配置參數
SVGA 庫配置
SVGA 播放器支持多種路徑配置,組件會自動嘗試以下路徑:
// 相對路徑(推薦)
require('../../static/js/svgaplayer.weapp.js');// 根目錄路徑
require('/static/js/svgaplayer.weapp.js');// 當前目錄路徑
require('./svgaplayer.weapp.js');
Canvas 配置
- 類型:
type="2d"
(推薦使用 2D Canvas) - 像素比: 自動適配設備像素比
- 大小: 支持響應式尺寸設置
最佳實踐
1. 性能優化
// 預加載動畫文件
const preloadAnimations = async () => {if (svgaPlayerRef.value) {await svgaPlayerRef.value.preload(animationUrl);}
};// 使用緩存避免重復加載
const svgaCollection = {}; // 在組件內部已實現緩存
2. 錯誤處理
// 監聽加載失敗
const handleAnimationError = () => {console.error('SVGA動畫加載失敗');// 顯示備用方案或錯誤提示
};
3. 內存管理
// 組件銷毀時清理資源
onUnmounted(() => {if (animationTemplateRef.value) {animationTemplateRef.value.stopAnimation();}
});
4. 平臺兼容
// 檢查平臺支持
const checkSVGASupport = () => {// 組件內部已處理平臺兼容性return typeof SVGA !== 'undefined';
};
常見問題
Q1: 動畫播放不顯示或報錯?
A1: 檢查以下幾點:
- 確認 SVGA 文件 URL 是否正確且可訪問
- 檢查 Canvas 元素是否正確渲染
- 查看控制臺是否有 SVGA 庫加載錯誤
Q2: 動畫播放卡頓或性能問題?
A2: 優化建議:
- 使用預加載功能提前加載動畫文件
- 控制動畫尺寸,避免過大的 Canvas
- 及時清理不需要的動畫實例
Q3: 在不同平臺表現不一致?
A3: 處理方案:
- 組件已內置多平臺適配邏輯
- 如遇問題,檢查是否使用了平臺特定的 API
- 確保 SVGA 文件格式符合標準
Q4: 動畫播放完成后如何處理?
A4: 使用回調函數:
animationRef.value.setOnFinished(() => {// 播放完成后的處理邏輯console.log('動畫播放完成');
});
示例代碼
完整使用示例
<template><view class="animation-demo"><!-- 觸發按鈕 --><button @click="startAnimation">開始播放動畫</button><!-- SVGA動畫組件 --><AnimationTemplateref="animationTemplateRef":animation-url="animationUrl":width="400":height="400":loops="1":show-close-button="true"position="center"@close="handleAnimationClose"@animationStart="handleAnimationStart"@animationEnd="handleAnimationEnd"/></view>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import AnimationTemplate from '@/components/AnimationTemplate/AnimationTemplate.vue';// 組件引用
const animationTemplateRef = ref(null);// 動畫配置
const animationUrl = 'https://static.wxb.com.cn/frontEnd/files/common/aidfinal1.svga';// 開始播放動畫
const startAnimation = () => {if (animationTemplateRef.value) {setupAnimationCallbacks();animationTemplateRef.value.startAnimation();}
};// 設置動畫回調
const setupAnimationCallbacks = () => {if (animationTemplateRef.value) {// 播放完成回調animationTemplateRef.value.setOnFinished(() => {console.log('SVGA動畫播放完成');animationTemplateRef.value.hide();uni.showToast({title: '動畫播放完成',icon: 'success',duration: 1500,});});// 幀回調(可選)animationTemplateRef.value.setOnFrame((frame) => {console.log('當前幀:', frame);});// 進度回調(可選)animationTemplateRef.value.setOnPercentage((percentage) => {console.log('播放進度:', Math.round(percentage * 100) + '%');});}
};// 事件處理
const handleAnimationClose = () => {console.log('動畫被手動關閉');
};const handleAnimationStart = () => {console.log('動畫開始播放');
};const handleAnimationEnd = () => {console.log('動畫播放結束');
};// 生命周期
onMounted(() => {// 可以在這里預加載動畫if (animationTemplateRef.value) {animationTemplateRef.value.preloadAnimation();}
});onUnmounted(() => {// 清理資源if (animationTemplateRef.value) {animationTemplateRef.value.stopAnimation();}
});
</script>
<style lang="scss" scoped>
.animation-demo {padding: 20rpx;
}
</style>
基礎播放器示例
<template><view class="basic-player"><SvgaPlayerref="svgaPlayerRef":url="animationUrl":width="300":height="300":canvas-id="'basicCanvas'":loops="0":clears-after-stop="false"/><view class="controls"><button @click="play">播放</button><button @click="pause">暫停</button><button @click="stop">停止</button></view></view>
</template>
<script setup>
import { ref } from 'vue';
import SvgaPlayer from '@/components/common/svgaPlayer.vue';const svgaPlayerRef = ref(null);
const animationUrl = 'https://static.wxb.com.cn/frontEnd/files/common/aidfinal1.svga';const play = () => {svgaPlayerRef.value?.startAnimation();
};const pause = () => {svgaPlayerRef.value?.pauseAnimation();
};const stop = () => {svgaPlayerRef.value?.stopAnimation(true);
};
</script>
總結
本 SVGA 動畫插件為項目提供了完整的矢量動畫播放解決方案,具有以下優勢:
- 高性能: 基于 Canvas 2D 渲染,支持硬件加速
- 跨平臺: 支持微信小程序、H5 等多端環境
- 易用性: 提供了簡單易用的組件 API
- 功能完整: 支持播放控制、回調監聽、預加載等功能
- 穩定性: 內置錯誤處理和資源管理機制
通過合理使用這些組件和 API,可以在項目中輕松實現高質量的動畫效果,提升用戶體驗。