微信小程序中使用lottie动画
微信小程序不支持动态加载canvas,所以如果想使用lottie动画,需要使用lottie小程序版本:
wechat-miniprogram/lottie-miniprogram: lottie for miniprogram (github.com)
npm i lottiejs-miniapp
页面中引入:
import * as lottie from 'lottiejs-miniapp'
使用:
html:
<canvas canvas-id="lottie" type="2d" id="lottie"/>
js:
data中:
data:{
anima: "",
}
init() {
wx.createSelectorQuery().select('#lottiejs-canvas').fields({ node: true, size: true }).exec(res => {
const canvas = res[0].node;
const ctx = canvas.getContext('2d');
const dpr = wx.getSystemInfoSync().pixelRatio;
canvas.width = res[0].width * dpr;
canvas.height = res[0].height * dpr;
ctx.scale(dpr, dpr);
lottie.setup(canvas);
this.anim = lottie.loadAnimation({
loop: true,
autoplay: true,
//animationData: animationData,
path: '你自己的lottie网络地址',
rendererSettings: {
context: ctx,
},
});
});
},
play() {
this.anim.play()
},
stop() {
this.anim.stop()
},
在onReady或onLoad中调用:
this.init()
需要把lottie绑定到this上,在通过this.来调用play或stop等方法。
注意小程序版的path仅支持网络地址