如何在微信小程序里使用Lottie動畫庫

先看效果圖:


1598250322634.gif

前言:

微信小程序的lottie動畫庫是按照lottie-web動畫庫改造而來。參考lottie-web:https://github.com/airbnb/lottie-web,以及官方文檔:http://airbnb.io/lottie/#/

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

調(diào)用lottie.loadAnimation()啟動動畫。它采用以下形式將對象作為唯一參數(shù):

  • animationData:具有導(dǎo)出的動畫數(shù)據(jù)的對象。
  • path:動畫對象的相對路徑。(animationData和path是互斥的)
  • loop:true/false
  • autoplay:true / false,準(zhǔn)備就緒后將立即開始播放
  • name:動畫名稱,以備將來參考
  • renderer:'svg'/'canvas'/'html'設(shè)置渲染器
  • container:在其上呈現(xiàn)動畫的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端的使用場景,那么我們?nèi)绾卧谛〕绦蛑惺褂媚兀?/h6>
  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 接口調(diào)用之前,需要傳入 canvas 對象

lottie.loadAnimation(options)**

與原來的 loadAnimation 有些不同,支持的參數(shù)有:

*   loop // 循環(huán)播放
*   autoplay //自動播放
*   animationData // 動畫數(shù)據(jù)
*   path //(只支持網(wǎng)絡(luò)地址)
*   rendererSettings.context //(必填)

json/data.js為找設(shè)計小姐姐要的Lottie動畫json數(shù)據(jù)。我們這邊需要將該json改為js。
即開頭需要加上module.exports=,當(dāng)然Lottie官方也收集了很多的動畫資源:https://lottiefiles.com/

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

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容