更新记录
v0.1.3(2026-07-08)
下载此版本
- 增加参数canvasId支持多实例
- 增加参数loop支持播放次数控制
- 修复预加载失败, 以及播放缓存失效
v0.1.2(2026-07-02)
下载此版本
增加preload参数,预加载svga资源
v0.1.1(2026-07-02)
下载此版本
调整背景层显示与svga播放时机一致
查看更多
平台兼容性
uni-app(3.7.13)
| Vue2 |
Vue3 |
Chrome |
Safari |
app-vue |
app-nvue |
Android |
iOS |
鸿蒙 |
| - |
√ |
√ |
√ |
- |
- |
- |
- |
- |
| 微信小程序 |
支付宝小程序 |
抖音小程序 |
百度小程序 |
快手小程序 |
京东小程序 |
鸿蒙元服务 |
QQ小程序 |
飞书小程序 |
小红书小程序 |
快应用-华为 |
快应用-联盟 |
| - |
- |
- |
- |
- |
- |
- |
- |
- |
- |
- |
- |
一个使用 svga 库封装的 uniapp H5 SVGA 播放组件示例项目
预览
安装依赖
pnpm install svga
基本使用
<script setup lang="ts">
import svgaPlayer from '@/components/svga-player/svga-player.vue'
const svgaPlayerRef = ref<InstanceType<typeof svgaPlayer>>()
const svgaUrl = new URL('@/static/svga/angel.svga', import.meta.url).href
onMounted(() => {
svgaPlayerRef.value?.play(svgaUrl)
})
</script>
<template>
<svga-player ref="svgaPlayerRef" />
</template>
完整示例
<script setup lang="ts">
import svgaPlayer from '@/components/svga-player/svga-player.vue'
const svgaPlayerRef = ref<InstanceType<typeof svgaPlayer>>()
const svga = [
new URL('@/static/svga/angel.svga', import.meta.url).href,
new URL('@/static/svga/rose.svga', import.meta.url).href,
]
const loop = ref(1)
onMounted(() => {
svgaPlayerRef.value?.play(svga[0])
svgaPlayerRef.value?.preload(svga[1])
})
async function handlePlay(url: string) {
await svgaPlayerRef.value?.play(url)
}
function handleStop() {
svgaPlayerRef.value?.stop()
}
function onReady() {
console.info('SVGA ready')
}
function onEnd() {
console.info('SVGA playback ended')
}
function onError(e: unknown) {
console.error('SVGA error:', e)
}
function onLoopChange(e: any) {
loop.value = e.detail.value
}
</script>
<template>
<view>
<slider :value="loop" :min="1" :max="10" show-value @change="onLoopChange" />
<button @click="handlePlay(svga[0])">天使</button>
<button @click="handlePlay(svga[1])">玫瑰</button>
<button @click="handleStop">停止</button>
<svga-player
ref="svgaPlayerRef"
:loop="loop"
canvas-id="svga-main"
@ready="onReady"
@end="onEnd"
@error="onError"
/>
</view>
</template>
Props 属性
| 属性名 |
类型 |
默认值 |
说明 |
| canvasId |
string |
'svga-container' |
Canvas 元素的 ID,用于挂载播放器 DOM 节点。同一页面使用多个播放器时需设置不同的 ID。 |
| loop |
number |
1 |
动画循环次数。设置为 0 表示无限循环。 |
Method 实例方法
| 方法名 |
参数 |
返回值 |
说明 |
| preload |
svgaUrl: string |
Promise<void> |
预加载 SVGA 动画。加载成功后再次 play 相同 URL 时可跳过加载直接播放。 |
| play |
svgaUrl: string |
Promise<void> |
播放指定的 SVGA 动画。若正在播放则忽略新请求。若 URL 已预加载则直接播放无需重新加载。 |
| stop |
无 |
void |
停止播放当前动画,并重置 playing 状态。 |
Events 事件
| 事件名 |
回调参数 |
说明 |
| ready |
无 |
SVGA 解析成功并挂载到播放器后触发。 |
| end |
无 |
动画播放完成(loop 次数耗尽)后触发。 |
| error |
error: unknown |
预加载、播放或容器初始化失败时触发。 |
工作流程
preload(url) ──→ 加载 + 挂载 SVGA ──→ 缓存到内存
│
play(url) ──→ 已缓存? ──→ 直接 start() ──→ onEnd()
未缓存? ──→ 重新加载 + 挂载 ──→ start()