Lottie是什么?
可以简单理解为不管是Android、还是IOS或者是h5、小程序都能通过它去加载同一动画文件,然后实现相同效果。
当然它也需要化身成各个平台的版本,今天介绍的就是小程序版本的Lottie
Lottie小程序效果
Lottie体验
Lottie安装到小程序
通过npm安装
1、根目录下打开终端输入
npm install --save lottie-miniprogram
2、接着输入
npm init
一直回车下去,直至执行完毕
3、打开微信开发者工具:工具>构建npm
Lottie小程序代码
js
const app = getApp()
import lottie from 'lottie-miniprogram'
Page({
data: {
lottiePath:""
},
onLoad: function () {
wx.getSystemInfo({
success: function(res) {
console.log(res)
},
})
var that = this
wx.cloud.getTempFileURL({
fileList: [{
fileID: 'cloud://normal-env-ta6pc.6e8/17008-loveduck.json',
maxAge: 60 * 60, // one hour
}]
}).then(res => {
that.setData({
lottiePath:res.fileList[0].tempFileURL
})
that.init()
}).catch(error => {
})
},
init() {
var that = this
if (this._inited) {
return
}
wx.createSelectorQuery().select('#canvas').node(res => {
const canvas = res.node
const context = canvas.getContext('2d')
canvas.width = 300
canvas.height = 300
lottie.setup(canvas)
this.ani = lottie.loadAnimation({
loop: true,
autoplay: false,
//远程动画
path:that.data.lottiePath,
//本地动画
// animationData: require('loveDuck.js'),
rendererSettings: {
context,
},
})
this._inited = true
}).exec()
},
play() {
this.ani.play()
},
pause() {
this.ani.pause()
},
})
wxml
<view class="intro">Lottie动画</view>
<view style="text-align: center;">
<canvas id="canvas" type="2d" style="display: inline-block; width: 300px; height: 300px;"></canvas>
<button bindtap="play" style="width: 300px;">play</button>
<button bindtap="pause" style="width: 300px;">pause</button>
</view>
json动画资源网站
lottie官网(很多设计师作品):https://lottiefiles.com
阿里设计网站(可自定义):https://design.alipay.com/emotion
问题
部分机型可能不支持加载远程动画