如何在微信小程序里使用Lottie动画库

先看效果图:
1598250322634.gif

前言:

微信小程序的lottie动画库是按照lottie-web动画库改造而来。参考lottie-web:https://github.com/airbnb/lottie-web,以及官方文档:http://airbnb.io/lottie/#/

目前我们要用到的是http://airbnb.io/lottie/#/web

调用lottie.loadAnimation()启动动画。它采用以下形式将对象作为唯一参数:

  • animationData:具有导出的动画数据的对象。
  • path:动画对象的相对路径。(animationData和path是互斥的)
  • loop:true/false
  • autoplay:true / false,准备就绪后将立即开始播放
  • name:动画名称,以备将来参考
  • renderer:‘svg’/‘canvas’/'html’设置渲染器
  • container:在其上呈现动画的dom元素

它返回您可以通过播放,暂停,setSpeed等控制的动画实例。

lottie.loadAnimation({
  container: element, // the dom element that will contain the animation
  renderer: 'svg',
  loop: true,
  autoplay: true,
  path: 'data.json' // the path to the animation json
});
以上为web端的使用场景,那么我们如何在小程序中使用呢?
  1. 通过 npm 安装:
npm install --save lottie-miniprogram
npm init
  1. 传入 canvas 对象用于适配
<view style="text-align: center;">
  <canvas id="lottie_demo" type="2d" style="display: inline-block; width: 300px; height: 300px;" />
  <button bindtap="init" style="width: 300px;">初始化</button>
  <button bindtap="play" style="width: 300px;">播放</button>
  <button bindtap="pause" style="width: 300px;">暂停</button>
</view>
  1. 使用lottie接口。
const app = getApp()
import lottie from 'lottie-miniprogram'

Page({
  data: {

  },
  // 初始化加载动画
  init() {
    if (this.inited) {
      return
    }
    wx.createSelectorQuery().selectAll('#lottie_demo').node(res => {
      const canvas = res[0].node
      const context = canvas.getContext('2d')
      canvas.width = 300
      canvas.height = 300
      lottie.setup(canvas)
      this.ani = lottie.loadAnimation({
        loop: true,
        autoplay: true,
        animationData: require('../json/data.js'),
        rendererSettings: {
          context,
        },
      })
      this.inited = true
    }).exec()
  },
  play() {
    this.ani.play()
  },
  pause() {
    this.ani.pause()
  },
})
目前微信小程序只提供了两个接口。
lottie.setup(canvas)

在任何 lottie 接口调用之前,需要传入 canvas 对象

lottie.loadAnimation(options)**

与原来的 loadAnimation 有些不同,支持的参数有:

*   loop // 循环播放
*   autoplay //自动播放
*   animationData // 动画数据
*   path //(只支持网络地址)
*   rendererSettings.context //(必填)

json/data.js为找设计小姐姐要的Lottie动画json数据。我们这边需要将该json改为js。
即开头需要加上module.exports=,当然Lottie官方也收集了很多的动画资源:https://lottiefiles.com/

module.exports={xxxxxx}
代码片段如下:

https://developers.weixin.qq.com/s/Ah3fGQmz7VjE

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值