当前位置: 首页 > news >正文

基于svga+uniapp的微信小程序动画组件开发指南

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 的封装组件,提供了更易用的动画展示模板。

主要特性:

  • 全屏遮罩展示
  • 支持多种位置布局(居中、顶部、底部)
  • 自动播放完成后隐藏
  • 支持手动关闭按钮

使用方法

基础使用

  1. 引入组件
<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>
  1. 程序化控制
// 开始播放动画
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

参数类型默认值说明
urlString必传SVGA 文件的 URL 地址
widthString/Number300动画宽度
heightString/Number300动画高度
canvasIdString‘svgaCanvas’Canvas 元素的 ID
loopsNumber1循环播放次数,0 表示无限循环
clearsAfterStopBooleanfalse播放完成后是否清除画布

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

参数类型默认值说明
animationUrlString必传SVGA 文件的 URL 地址
widthString/Number300动画宽度
heightString/Number300动画高度
canvasIdString‘animationTemplateCanvas’Canvas 元素的 ID
loopsNumber1循环播放次数
clearsAfterStopBooleanfalse播放完成后是否清除画布
showCloseButtonBooleantrue是否显示关闭按钮
backgroundOpacityNumber0.5背景遮罩透明度
positionString‘center’动画位置:‘center’, ‘top’, ‘bottom’
zIndexNumber9999层级索引

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 动画插件为项目提供了完整的矢量动画播放解决方案,具有以下优势:

  1. 高性能: 基于 Canvas 2D 渲染,支持硬件加速
  2. 跨平台: 支持微信小程序、H5 等多端环境
  3. 易用性: 提供了简单易用的组件 API
  4. 功能完整: 支持播放控制、回调监听、预加载等功能
  5. 稳定性: 内置错误处理和资源管理机制

通过合理使用这些组件和 API,可以在项目中轻松实现高质量的动画效果,提升用户体验。


http://www.lryc.cn/news/583215.html

相关文章:

  • 前端进阶之路-从传统前端到VUE-JS(第四期-VUE-JS页面布局与动态内容实现)(Element Plus方式)
  • IntelliJ IDEA 2025.1.3创建不了java8的项目
  • 【PTA数据结构 | C语言版】大整数相加运算
  • Linux驱动05 --- TCP 服务器
  • PostgreSQL如何进行跨服务器迁移数据
  • 70、【OS】【Nuttx】【构建】配置 stm32 工程
  • OpenGL 生成深度图与点云
  • 记一次接口优化历程 CountDownLatch
  • 景观桥 涵洞 城门等遮挡物对汽车安全性的影响数学建模和计算方法,需要收集那些数据
  • 【软件运维】前后端部署启动的几种方式
  • Live555-RTSP服务器
  • Linux——I/O复用
  • 零知开源——STM32F407VET6驱动SHT41温湿度传感器完整教程
  • Linux 中的 .bashrc 是什么?配置详解
  • Python 初识网络爬虫:从概念到实践
  • 什么是公链?
  • 微软 Bluetooth LE Explorer 实用工具的详细使用分析
  • 新零售“云化”进化:基于定制开发开源AI智能名片S2B2C商城小程序的探索
  • 【视频观看系统】- 技术与架构选型
  • HashMap源码分析:put与get方法详解
  • 爬楼梯及其进阶
  • Kubernetes 存储入门
  • 由 DB_FILES 参数导致的 dg 服务器无法同步问题
  • 搭建一款结合传统黄历功能的日历小程序
  • 汽车智能化2.0引爆「万亿蛋糕」,谁在改写游戏规则?
  • A1220LUA-T Allegro高精度霍尔效应开关 车规+极致功耗+全极触发 重新定义位置检测标准
  • 【Gin】HTTP 请求调试器
  • 微软官方C++构建工具:历史演变、核心组件与现代实践指南
  • Rust与Cypress应用
  • 在Ubuntu上安装配置 LLaMA-Factory