介绍:
lottie动画简单高效,动画文件小,丝滑流畅,动画可控性强。只支持json文件,文件可以由UI设计师提供,通过AE(After Effects)制作动画,再通过 AE 插件 Bodymovin 导出 json 文件,也可以通过阿里图标库iconfont进行下载(有版权)。
一、安装lottie-web
npm i lottie-web
二、lottie 动画的 json 文件放入 src/assets 文件夹中
三、本地动画需要在 vue 文件中引入 json 文件(网络动画则不需要引入)
// 本地assets json文件
import bg from "../assets/bg.json"
四、组件封装lottie.vue
<template>
<div ref="dom" :style="{ width, height }"></div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import lottie from 'lottie-web'
const props = defineProps({
width: {
type: String,
default: '100%',
},
height: {
type: String,
default: '100%'
},
path: {
type: String
},
jsonData: {
type: Object
},
renderer: {
type: String,
default: 'svg'
},
autoplay: {
type: Boolean,
default: true
},
loop: {
type: Boolean,
default: true
}
})
let dom = ref(null)
let animation = reactive({})
onMounted(() => {
if (dom.value) {
animation = lottie.loadAnimation({
container: dom.value, // 渲染的DOM
renderer: props.renderer, // 渲染方式 svg | canvas | html
loop: props.loop, // 循环播放
autoplay: props.autoplay, // 自动播放
path: props.path, // 网络json地址
animationData: props.jsonData, // 加载本地json,优先于path
})
}
})
五、index.vue 引入组件
<template>
<div style="width: 200px; height: 200px; margin: 2vw auto">
<Lottie :jsonData="bg" />
</div>
</template>
<script setup>
import Lottie from "../components/lottie.vue"
import bg from "../assets/bg.json"
</script>
常用方法
animation.pause();//暂停
animation.play();//播放
animation.stop();//停止
animation.destroy();//销毁