uniapp开发微信小程序使用lottie动画
王毛毛 Lv1

效果

PixPin_2025-07-01_13-44-58

实现

安装lottie依赖包

npm install lottie-miniprogram

在界面引入依赖包

1
import lottie from 'lottie-miniprogram';

画布准备

1
2
3
4
5
6
<canvas
id="Mycanvas"
ref="canvas"
type="2d"
style="width:600rpx;height:400rpx;"
/>

初始化方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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();
};
Powered by Hexo & Theme Keep
Unique Visitor Page View