Qiitaに投稿するために書いている途中です
きっかけ
Lottie動画の取り扱いが初めてだったので備忘録を兼ねて投稿。
構築中のサイトのヘッダーキャッチ背景に動画を設定することになった。
デザイナーさんがAdobe After Effectsで作成してくれた動画だったけど、SVG動画として書き出すことはできないので、Lottieを利用して実装できるようにAfter EffectsにBodymovinプラグインをインストールしてJSON形式で書き出ししてくれた。
■参照:Lottieとは?
■参考にしたサイト:Bit Beans
ディレクトリ構成
src -- assets
| |- animation
| |- animation.json // 今回背景にする動画
|- components
| |- LottieAnimaton.vue // 動画用コンポーネント
|- pages
| |- index.vue // 表示するファイル
|- nuxt.config.ts
|- plugins
|- lottie.ts // プラグインファイル
- lottie.ts を作成する
// ~/plugins/lottie.ts import { defineNuxtPlugin } from '#app' import lottie from 'lottie-web' export default defineNuxtPlugin((nuxtApp) => { nuxtApp.provide('lottie', lottie) })
- nuxt.config.tsにlottie.tsを追加する
export default defineNuxtConfig({ plugins: [ '~/plugins/lottie.ts', ], });
- LottieAnimaton.vue を作成する
<script setup lang="ts"> import { ref, onMounted, defineProps, defineEmits } from 'vue' import lottie from 'lottie-web' // propsの定義 const props = defineProps({ animationData: { type: Object, required: true, }, loop: { // ループ再生するかどうか type: Boolean, default: true, }, autoplay: { // 自動再生するかどうか type: Boolean, default: true, }, width: { // アニメーションの幅 type: String, default: '100%', }, height: { // アニメーションの高さ type: String, default: '100%', }, }) const emit = defineEmits(['animCreated']) // コンテナの参照 const lavContainer = ref(null) // コンポーネントがマウントされた後の処理 onMounted(() => { if (lavContainer.value) { const anim = lottie.loadAnimation({ container: lavContainer.value, renderer: 'svg', loop: props.loop, autoplay: props.autoplay, animationData: props.animationData, }) emit('animCreated', anim) } }) </script>
- 表示するファイル(index.vue)を作成する
<template> <div> <LottieAnimation :options="defaultOptions" width="100%" height="100%" class="introduction__background" @anim-created="handleAnimation" /> </div> </template> <script lang="ts" setup> import animationData from '@/assets/animation/animation.json' const defaultOptions = ref({ loop: true, autoplay: true, animationData: animationData, }) const show = ref(true) const anim = ref(null) onMounted(() => { setTimeout(() => { show.value = false }, 7000) }) function handleAnimation(animInstance) { anim.value = animInstance } </script>