F2e踩坑之路

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

2020-08-24  本文已影响0人  人类进化又没带我

先看效果图:


1598250322634.gif

前言:

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

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

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

它返回您可以通过播放,暂停,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

上一篇 下一篇

猜你喜欢

热点阅读