效果

实现
安装lottie依赖包
npm install lottie-miniprogram
在界面引入依赖包
vue
import lottie from 'lottie-miniprogram';
画布准备
VUE
<canvas
id="Mycanvas"
ref="canvas"
type="2d"
style="width:600rpx;height:400rpx;"
/>
初始化方法
JS
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 canvas
lottie.setup(canvas);
console.log(svgaData)
try {
// 加载动画数据
const lottieRef = lottie.loadAnimation({
loop: true,
autoplay: true,
// 使用本地动画数据文件
// animationData: svgaData,
// 或者使用远程 URL
path: '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();
};