1.介绍
Lottie是Airbnb开发的一种轻量级的JavaScript库,它能够在Web、iOS和Android平台上呈现高质量、动态的矢量动画。Lottie使得在应用中使用复杂的矢量动画变得更加容易,并且在不同平台上能够实现更高的视觉一致性。而lottie-web是Lottie的Web版本,使用它可以在Web页面中展示高品质、流畅的动态矢量动画。
2.常见的播放动画方式
1.css 的 animation或者transition
- 优点: 使用比较简单
- 缺点: 对于 500+帧的情况,动画播放需要依赖于图片是否下载成功,500+帧图片的下载,势必会导致动画卡顿
2.gif
- 优点: 使用简单,只需要设计同学给一张图片即可
- 缺点: gif图是位图,不是矢量图,放大会虚
3.lottie-web
-
优点:
1.使用 lottie 方案,json 文件大小会比 gif 文件小很多,性能也会更好;
2.lottie是一个不太占体积,还原度高,对于初学者友好的库
3.前端直接引用lottie-web库即可,它默认的渲染方式是svg,原理就是用JS操作Svg API -
缺点:
1.lottie-web 文件本身仍然比较大,lottie.js 大小为 513k,轻量版压缩后也有 144k,经过 gzip 后,大小为 39k。
2.有很少量的 AE 动画效果,lottie 无法实现,有些是因为性能问题,有些是没有做。比如:描边动画等;
3.lottie-web 的使用
1.安装
npm install lottie-web -S
2.封装通用的动画组件
MyLottie.vue
<template>
<div
class='lottie'
:style='{width,height}'
ref='lavContainer'
>
<slot/>
</div>
</template>
<script>
import lottie from 'lottie-web'
export default {
props: {
options: {
type: Object,
default: () => ({}),
},
width: {
type: String || Number,
default: '100%',
},
height: {
type: String || Number,
default: '100%',
},
},
data () {
return {
anim: {},
}
},
mounted () {
this.anim = lottie.loadAnimation({
container: this.$refs.lavContainer,
renderer: 'svg',
loop: this.options.loop !== false, // 是否循环播放动画
autoplay: this.options.autoplay !== false, // 是否自动播放动画
// 动画数据
animationData: this.options.animationData.default ? this.options.animationData.default : this.options.animationData,
rendererSettings: this.options.rendererSettings,
})
this.$emit('animCreated', this.anim)
},
}
</script>
3.在页面中的使用
<template>
<my-lottie
:options='animOptions'
width='200px'
height='200px'
@animCreated='animLoaded'
/>
</template>
<script>
import * as animationData from '@/assets/lottie/analysis-animation.json'
import MyLottie from '@/components/MyLottie'
export default {
components: { MyLottie },
data () {
return {
// 解析过程动画配置
animOptions: {
animationData,
anim: null,
},
}
},
methods: {
// 动画初始化后的回调 返回动画的对象
animLoaded (anim) {
this.anim = anim
},
},
}
</script>