当前位置:首页 > JavaScript > 微信小程序中使用lottie动画

微信小程序中使用lottie动画

一叶知秋2024-04-07 15:10:30JavaScript5

微信小程序不支持动态加载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仅支持网络地址

扫描二维码推送至手机访问。

版权声明:本站部分文章来自AI创作、互联网收集,请查看免责申明

本文链接:https://www.yyzq.team/post/331960.html

分享给朋友: