闽公网安备 35020302035485号
Lottie 是一个由 Airbnb 开源的动画库,它允许你在 Web、iOS、Android 等平台上使用体积小、高性能的体验丰富的矢量动画。本文将详细介绍在 Vue 项目中如何集成和使用 Lottie。
npm install lottie-web # 或 yarn add lottie-web步骤二:引入 Lottie
// HelloWorld.vue
// 堆代码 duidaima.com
<template>
<div>
<lottie
:options="lottieOptions"
:width="400"
:height="400"
/>
</div>
</template>
<script>
import Lottie from 'lottie-web';
import animationData from './path/to/your/animation.json';
export default {
data() {
return {
lottieOptions: {
loop: true,
autoplay: true,
animationData: animationData,
},
};
},
mounted() {
this.$nextTick(() => {
// 初始化 Lottie 动画
const lottieInstance = Lottie.loadAnimation(this.lottieOptions);
});
},
};
</script>
<style>
/* 可以添加样式以调整动画的位置和大小 */
</style>
在上述代码中,animationData 是你的动画 JSON 数据,可以使用 Bodymovin 插件将 After Effects 动画导出为 JSON。
/* HelloWorld.vue */
<style>
.lottie {
margin: 20px auto; /* 调整动画的位置 */
}
</style>
// 使用 DOM 元素作为容器
const container = document.getElementById('animation-container');
// 或者使用 CSS 选择器字符串
const container = '#animation-container';
// 初始化 Lottie 动画
const animation = lottie.loadAnimation({
container: container,
/* 其他配置参数... */
});
2. rendererconst animation = lottie.loadAnimation({
container: '#animation-container',
renderer: 'svg', // 或 'canvas'
/* 其他配置参数... */
});
const animation = lottie.loadAnimation({
container: '#animation-container',
loop: true,
/* 其他配置参数... */
});
4. autoplayconst animation = lottie.loadAnimation({
container: '#animation-container',
autoplay: true,
/* 其他配置参数... */
});
5. pathconst animation = lottie.loadAnimation({
container: '#animation-container',
path: 'path/to/animation.json',
/* 其他配置参数... */
});
6. rendererSettingsconst animation = lottie.loadAnimation({
container: '#animation-container',
rendererSettings: {
clearCanvas: true, // 在每一帧上清除画布
},
/* 其他配置参数... */
});
7. animationDataconst animationData = {
/* 动画数据的具体内容 */
};
const animation = lottie.loadAnimation({
container: '#animation-container',
animationData: animationData,
/* 其他配置参数... */
});
8. nameconst animation = lottie.loadAnimation({
container: '#animation-container',
name: 'myAnimation',
/* 其他配置参数... */
});
9. speedconst animation = lottie.loadAnimation({
container: '#animation-container',
speed: 1.5, // 播放速度为原来的1.5倍
/* 其他配置参数... */
});
10. 事件回调const animation = lottie.loadAnimation({
container: '#animation-container',
loop: true,
onComplete: () => {
console.log('动画完成!');
},
/* 其他配置参数... */
});
通过灵活使用这些参数,你可以定制化你的动画,使其更好地满足项目的需求。npm run serve # 或 yarn serve
访问 http://localhost:8080(具体端口可能会有所不同),你应该能够看到嵌入的 Lottie 动画正常播放。