先看效果圖:
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端的使用場景,那么我們如何在小程序中使用呢?
- 通過 npm 安裝:
npm install --save lottie-miniprogram
npm init
- 傳入 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>
- 使用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}