基于lottie的微信小程序动画开发指南
svga动画开发指南
效果
实现
安装lottie依赖包
npm install lottie-miniprogram
在界面引入依赖包
import lottie from 'lottie-miniprogram';
画布准备
<canvasid="Mycanvas"ref="canvas"type="2d"style="width:600rpx;height:400rpx;"
/>
初始化方法
onMounted(() => {// 初始化 Lottie 动画initLottieAnimation();});const initLottieAnimation = () => {uni.createSelectorQuery().select('#Mycanvas').node(res => {if (!res || !res.node) {console.error('Canvas node not found');return;}const canvas = res.node;const context = canvas.getContext('2d');// 获取设备像素比,确保动画清晰度const dpr = uni.getSystemInfoSync().pixelRatio || 1;canvas.width = 600 * dpr;canvas.height = 400 * dpr;// 缩放canvas上下文以匹配设备像素比context.scale(dpr, dpr);// 设置 Lottie canvaslottie.setup(canvas);console.log(svgaData)try {// 加载动画数据const lottieRef = lottie.loadAnimation({loop: true,autoplay: true,// 使用本地动画数据文件// animationData: svgaData,// 或者使用远程 URLpath: 'https://msd.junongshupin.com/FILES/miniapp/anim/lf20_2BmOqX.json',rendererSettings: { context,},});// 添加动画事件监听lottieRef.addEventListener('complete', () => {console.log('Lottie animation completed');});lottieRef.addEventListener('loopComplete', () => {console.log('Lottie animation loop completed');});lottieRef.addEventListener('error', (error) => {console.error('Lottie animation error:', error);});} catch (error) {console.error('Lottie animation load failed:', error);}}).exec();
};