不要问为什么 没有为什么。浮躁的7月首周。Keep Going And Stay Strong。
Lottie是一个IOS,Android和React Native库,可以实时渲染动画,动画被转化成JSON文件,节省了很多资源,允许应用程序像使用静态图像一样轻松使用动画,主要是展示型的动画,交互的不太好实现。网上也有丰富的动画资源,点此进入LottieFiles,里面可以直接下载JSON格式的动画文件,很炫酷。还有可以自己编辑Lottie动画的工具LottieEditor。
这里主要讲Vue项目里使用Lottie,简单封装一个展示动画的通用组件,原生的不太会搞,然后还搜了一下原理,没看懂。
上图。
1.vue-lottie安装
npm install --save vue-lottie
2. 简单封装
<template><div ref="lavContainer"></div>
</template><script lang="ts">
import { Component, Ref, Vue, Prop, Emit } from "vue-property-decorator";
import lottie from "lottie-web";@Component
export default class Lottie extends Vue {@Prop() options!: any;@Ref() readonly lavContainer!: HTMLElement;anim!: Object;mounted() {this.anim = lottie.loadAnimation({container: this.lavContainer,renderer: "svg",loop: true,autoplay: true,animationData: this.options.animationData,rendererSettings: this.options.rendererSettings});this.$emit("animCreated", this.anim);}
}
</script>
3.使用
里面加了 停止stop() 播放play() 暂停pause() 方法,并且可以设置动画速度。
animationData 是动画的Json格式。
<template><div><Lottiev-if="show":options="defaultOptions"style="width:200px;"v-on:animCreated="handleAnimation"/><div @click="switchLottie">点击开始</div><div v-if="show"><p>Speed: x{{ animationSpeed }}</p><inputtype="range"value="1"min="0"max="3"step="0.5"@change="onSpeedChange"v-model="animationSpeed"/><br /><button @click="stop">stop</button><button @click="pause">pause</button><button @click="play">play</button></div></div>
</template><script lang="ts">
import { Component, Ref, Vue, Provide } from "vue-property-decorator";
import Lottie from "./Lottie.vue";
import animationData from "@/assets/gif/loader.json";@Component({components: { Lottie }
})
export default class Test extends Vue {defaultOptions = { animationData: animationData };animationSpeed: number = 1;anim?: any;show = false;switchLottie() {this.show = !this.show;}handleAnimation(a: object) {this.anim = a;}stop() {this.anim.stop();}play() {this.anim.play();}pause() {this.anim.pause();}onSpeedChange() {this.anim.setSpeed(this.animationSpeed);}
}
</script>
相关网站:
官网:https://airbnb.design/lottie/
gayHub: https://github.com/airbnb/lottie-web
Lottie 库和插件:https://lottiefiles.com/
轮子工厂:http://www.wheelsfactory.cn/
可编辑Lottie动画工具: https://github.com/sonaye/lottie-editor