Use lottie-web on the front end, and use the JSON animation exported by AE to provide an intimate tutorial

Introduction to Lottie

Official introduction: Lottie is a library that can analyze animations made with AE (need to use bodymovie to export to json format), and supports web, ios, android, flutter and react native. On the web side, the lottie-web library can parse the exported animation json file and draw the animation on our page in the form of svg or canvas.

Advantages of Lottie

  1. The animation is realized by designing and using the professional animation production tool AE, which makes the animation more convenient and the effect is better
  2. The front-end can easily call animation and control the animation, reducing the workload of front-end animation
  3. Design and produce animation, front-end display animation, clear division of labor
  4. Using the lottie scheme, the json file size is much smaller than the gif file, and the performance will be better

The use of lottie-web in the front end

  1. Install lottie-web
npm install lottie-web
复制代码
  1. Basic usage of lottie-web
import lottie from 'lottie-web'

const animation = lottie.loadAnimation({
    
    
  container: document.getElementById('domId'), // 绑定dom节点
  renderer: 'svg', // 渲染方式:svg、canvas
  loop: true, // 是否循环播放,默认:false
  autoplay: true, // 是否自动播放, 默认true
  animationData: // AE动画使用bodymovie导出为json数据
})
  1. json simple explanation
{
    
    
    "v": "5.1.13",       // bodymovin 版本
    "fr": 30,            // 帧率
    "ip": 0,             // 起始关键帧
    "op": 20,            // 结束关键帧
    "w": 150,            // 视图宽
    "h": 130,            // 视图高
    "nm": "鹅头收起动画",  // 名称
    "ddd": 0,             // 3d
    "assets": [],        // 资源集合 
    "layers": [],        // 图层集合
    "masker": []         // 蒙层集合
}
  1. Common methods of lottie-web We initialized a lottie object before. Then we introduce some common methods of it
animation.play(); // 播放,从当前帧开始播放

animation.stop(); // 停止,并回到第0帧

animation.pause(); // 暂停,并保持当前帧

animation.goToAndStop(value, isFrame); // 跳到某个时刻/帧并停止isFrame(默认false)指示value表示帧还是时间(毫秒)

animation.goToAndPlay(value, isFrame); // 跳到某个时刻/帧并进行播放

animation.goToAndStop(30, true); // 跳转到第30帧并停止

animation.goToAndPlay(300); // 跳转到第300毫秒并播放

animation.playSegments(arr, forceFlag); // arr可以包含两个数字或者两个数字组成的数组,forceFlag表示是否立即强制播放该片段

animation.playSegments([10,20], false); // 播放完之前的片段,播放10-20帧

animation.playSegments([[0,5],[10,18]], true); // 直接播放0-5帧和10-18帧

animation.setSpeed(speed); // 设置播放速度,speed为1表示正常速度

animation.setDirection(direction); // 设置播放方向,1表示正向播放,-1表示反向播放

animation.destroy(); // 删除该动画,移除相应的元素标签等。

Lottie-web commonly used events

animation.addEventListener('data_ready', () => {
    
    }) // 动画数据加载完毕
animation.addEventListener('config_ready', () => {
    
    }) // 完成初始配置后
animation.addEventListener('data_failed', () => {
    
    }) // 加载动画数据失败
animation.addEventListener('loaded_images', () => {
    
    }) // 所有图片加载成功或者失败
animation.addEventListener('DOMLoaded', () => {
    
    }) // 将元素添加到DOM后
* complete: 播放完成(循环播放下不会触发)
* loopComplete: 当前循环下播放(循环播放/非循环播放)结束时触发
* enterFrame: 每进入一帧就会触发,播放时每一帧都会触发一次,stop方法也会触发
* segmentStart: 播放指定片段时触发,playSegments、resetSegments等方法刚开始播放指定片段时会发出,如果playSegments播放多个片段,多个片段最开始都会触发。
* data_ready: 动画json文件加载完毕触发
* DOMLoaded: 动画相关的dom已经被添加到html后触发
* destroy: 将在动画删除时触发

Lottie's Free Resources

The animation we mentioned before Lottieis created in AE and then exported to json format using bodymovie. In fact, there is a website that provides some free animations (of course there are also paid ones) that directly have the animation json data we need.

image.png

As shown in the animation below, we find the animation we want, and after clicking, a pop-up window pops up, click to download, and the format is JSON. Then we can use the json data of this animation in our own project.QQ20210711-211633-HD.gif

Well, after introducing its usage, let's go to vueChina to do an actual combat

Using lottie in vue

  1. Use vite to run vue
npm init @vitejs/app <project-name>
复制代码
  1. Install lottie-web
npm install lottie-web
复制代码
  1. To encapsulate a basic component lottie.vue, the main thing is to initialize the lottie object, and then pass the object to other components for use
<template>
  <div :style="style" ref="lavContainer"></div>
</template>

<script>
import lottie from ‘lottie-web’

export default {
name: ‘lottie’,
props: {
options: {
type: Object,
required: true,
},
height: Number,
width: Number,
},

computed: {
style() {
return {
width: this.width ? <span class="hljs-subst">${<span class="hljs-variable language_">this</span>.width}</span>px : ‘100%’,
height: this.height ? <span class="hljs-subst">${<span class="hljs-variable language_">this</span>.height}</span>px : ‘100%’,
}
},
},

mounted() {
this.anim = lottie.loadAnimation({
container: this.KaTeX parse error: Expected 'EOF', got '}' at position 798: …ta</span>, }̲) <span cla…emit(‘animCreated’, this.anim)
},

unmounted () {
this.anim && this.anim.destroy()
}
}
</script>

copy code

  1. Based on the above components, we encapsulate a more concrete component clickIcon, which is also a general component, adding logic such as how to move the animation interaction after clicking.
<template>
  <div class="clickIcon">
    <div
      class="iconBox"
      :style="{ width: width + 'px', height: height + 'px' }"
    >
      <slot name="svg" v-bind:data="{ toggle, flag, iconWidth, iconHeight }"></slot>
      <lottie
        @click="toggle"
        :class="{ show: flag === true || !defaultSlot }"
        class="like"
        style="display: none;"
        :options="options"
        :height="height"
        :width="width"
        v-on:animCreated="handleAnimation"
      />
    </div>
  </div>
</template>

<script>
import { computed, ref, defineComponent } from “vue”;
import Lottie from “./lottie.vue”;
let anim = null
/**

  • Click on the icon and then play an animation component
  • Suitable for small functions such as favorites and likes
    */

export default defineComponent ({ name : “clickIcon” , props : { // width width : { type : Number , default : 100 , }, // height height : { type : Number , default : 100 , }, // initialize Lottie Required parameters options : { type : Object , default : () => {}, }, // Whether a slot is required to display a default icon


















defaultSlot : { type : Boolean , default : true }, // The interaction effect required after a click passed from outside toggleFun : { type : Function , default : null } }, components : { lottie : Lottie , }, emits : [ 'init' ], setup ( props, { emit } ) { // animation speed const animationSpeed ​​= 2 // click on the interaction flag let flag = ref (

















false );
// icon height
const iconWidth = computed ( () => { return props. width ; }); // icon width const iconHeight = computed ( () => { return props. height ; }); // click icon interaction const toggle = function (







) {
if (!props.defaultSlot) {
props.toggleFun && props.toggleFun(anim)
} else {
flag.value = !flag.value;
if (flag.value) {
anim.play();
} else {
anim.stop();
}
}
};
// 获取anim对象
const handleAnimation = function(animated) {
anim = animated;
onSpeedChange()
emit( 'init' , animated)
}
// stop animation
const stop = function () { anim.stop (); } // play animation const play = function (



) { anim.play (); } // pause the animation const pause = function (



) { anim.pause (); } // Control playback speed const onSpeedChange = function (



) {
anim.setSpeed(animationSpeed);
}
return {
iconWidth,
iconHeight,
handleAnimation,
flag,
toggle,
stop,
play,
pause
};
},
});
</script>

<style scoped>
.iconBox {
position: relative;
}
.show {
display: inline-block !important;
}
.hidden {
display: none !important;
}
.like {
cursor: pointer;
}
.icon {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%)

; } </style> Copy code

Next, we will write a 喜欢component like.vue, as we have seen before, QQ20210711-211633-HD.giffirst put the downloaded animation json file into the resource file directory, and then we will use the code to call it.

<template>
  <lottie
    class="like"
    :options="defaultOptions"
    :height="height"
    :defaultSlot="false"
    :width="width"
    @init="init"
    :toggleFun="toggle"
    ref="lottie"
  >
  </lottie>
</template>

<script>
import Lottie from “…/common/clickIcon.vue”;
import animationData from “/public/like.json”;

export default {
name: “app”,
components: {
lottie: Lottie,
},
props: {
width: {
type: Number,
default: 60,
},
height: {
type: Number,
default: 60,
},
},
methods: {
init (animation) {
animation && animation.goToAndStop(0, true)
},
toggle (animation) { if ( this . toggleFlag ) { animation. playSegments ([ 50 , 90 ], true ); // play from frame 50 to the end } else { animation && animation. playSegments ([ 0 , 50 ] , true ); // Play from frame 0 to frame 50 } this . toggleFlag = ! this . toggleFlag } }, data (








) {
return {
toggleFlag: false,
defaultOptions: {
name: “like”,
animationData: animationData,
autoplay: false,
loop: false,
}
};
}
};
</script>

<style scoped>
.hidden {
display: none;
}
</style>

copy code

The reason for the above effect is that the json file of the 'like' animation we downloaded is composed of two states, 0-50 frames are animations from unselected to selected states, and 50->90 frames are Selected state -> animation of unselected state. The specific number of frames to how many frames can be seen from the progress of the window below the window where the json file is downloaded from the website.

  1. use 喜欢components
<template>
  <div id="app">
    <like></like>
  </div>
</template>

<script>
import { defineComponent } from “vue”;
import like from “./components/like/index.vue”;

export default defineComponent ({ components : { like, }, }); Copy code




The specific effect is as follows

QQ20210711-214951-HD.gif

epilogue

喜欢The above is to use Lottie to implement a component in vue . In fact, I just wrote such a demo at the moment. If you are interested, you can implement it again. Now the component has not recorded the default state of the component. It may be selected by default. In addition, we got it this time. The animation component just has two states: selected and unselected. There are still some animations in the website for free downloading animation json files that I introduced to you before, which only give a selected animation effect, and there is no unselected state. At this time, we can find a similar svg icon by ourselves, and then use it as the default icon. After clicking, the selected animation effect will be triggered. This kind of scene is rarely encountered. If it is a company project, you can ask the artist to do two The animation effect of the state, if it is your own personal project, and then you come across a free animation that you like very much, but it only provides one state, then it is only useful at this time. I actually took this situation into consideration in the component, that is, defaultSlotset this property to true, and then add a slot as a default component when writing the component.

write at the end

Can everyone give a like to encourage Mengxin? Hahaha, thank you in advance~

Guess you like

Origin blog.csdn.net/qq_32594913/article/details/128606420