vue 에서 lottie 사용하기 예제 example > IT 기술백서

IT 기술백서

직접 알아내거나 검색하기 귀찮아서 모아 둔 것

JavaScript | vue 에서 lottie 사용하기 예제 example

본문

1. lottie-web 을 설치한다.

[code]

$ yarn add lottie-web

[/code]

 

2. lottie 용 컴포넌트를 만든다.

참고: https://www.npmjs.com/package/vue-lottie

FileName: /components/controls/Lottie.vue

[code]

<template>

  <div ref="lavContainer" :style="style"></div>

</template>


<script>

import lottie from 'lottie-web'

export default {

  props: {

    options: {

      type: Object,

      required: true,

    },

    height: {

      type: [Number, String],

      required: false,

      default: '100%',

    },

    width: {

      type: [Number, String],

      required: false,

      default: '100%',

    },

  },

  data() {

    return {

      style: {

        width: this.width ? `${this.width}px` : '100%',

        height: this.height ? `${this.height}px` : '100%',

        overflow: 'hidden',

        margin: '0 auto',

      },

    }

  },

  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,

      rendererSettings: this.options.rendererSettings,

    })

    this.$emit('animCreated', this.anim)

  },

}

</script>

 

 

[/code]

 

3. 사용예제

[code]

<template>

  <div class="test">

    <lottie

      :options="defaultOptions"

      :height="400"

      :width="400"

      @animCreated="animCreatedHandler"

    />

    <v-btn @click="doStart">시작</v-btn>

    <v-btn @click="doStop">중지</v-btn>

  </div>

</template>

 

data.js

[code]

/**

data 파일이 json 형식이면 require 를 사용 못하기 때문에 js 파일로 만들어 준다.

**/

const data = {

   ....

}

export default data

[/code]


Example.vue

<script>

import lottie from '~/components/controls/Lottie'

import animationData from '~/assets/ani/data.js' // 애니메이션 데이터


export default {

  components: {

    lottie,

  },

  data() {

    return {

      title: '테스트',

      anim: null,

      defaultOptions: {

        animationData: animationData, // json 파일일때는 animationData.default

        loop: false,

      },

    }

  },

  methods: {

    // 애니메이션이 생성되면 호출된다.

    animCreatedHandler(anim) {

      // 객체 저장

      this.anim = anim

      // 사용하고자 하는 이벤트 핸들러를 등록한다.

      this.anim.addEventListener('complete', (e) => {

        console.log('Animation Complete!')

        console.log(e)

      })

    },

    // 시작 

    doStart() {

      this.anim.stop() // stop 하지않고 play() 만 하면 다음번엔 움직이지 않는다.

      this.anim.play()

    },

    doStop() {

      this.anim.stop()

    },

  },

}

</script>

[/code]

 

※ lottie 옵션과 이벤트는 아래를 참조한다.

https://github.com/airbnb/lottie-web

댓글 0개

등록된 댓글이 없습니다.

Menu