透過 Adobe After Effect 製作 lottie 動畫,並與 Javascript 互動 Part 1 - 動態替換文字
前言
公司想製作猴子上樹的小遊戲,起因是原本專案有用到 Lottie 動畫,覺得動畫流暢度及體驗感很好,就深入研究了一下,如何用 Adobe After Effect 製作 Lottie 小遊戲動畫,並與 Vue 前端框架做互動。
前置準備
- 安裝 Adobe After Effeect
- 安裝 Bodymovin 插件 ( for 匯出 lottie的 json )
- 開啟『允許腳本及網路存取』
勾選 Allow Script to write file and network access
讓我們開始開發吧
首先,我們得匯入 Lottie 素材,至 Adobe After Effec
我們可以透過 lottiefiles.com 下載免費的lottie 動畫 json 檔。
回到 Adobe After effect ,點選 Window > Extensions > Bodymovin
點選 Import Lottie Anmimation >
匯入剛剛的下載的lottie 的動畫 json 檔
匯入成功的畫面
匯入的動畫會顯示在素材庫裡
埋入文字圖層 (Text Layer) 給 Javascript 控制
點選輸入 horizontal type tool > 輸入文字 > “test”
對 text layer > 右鍵 > rename
但這邊要非常注意,因為後面要透過 Javascript 控制,因此要透過 “#” 當特殊後缀命名,#字之後字元會轉換成 id。 emample: test#rate
最後輸出在網頁的時候,會將 id 挷在所屬的 DOM 上
匯出 lottie json 動畫檔
開啟Bodymovin, Window > Extensions > Bodymovin ,並依據下圖操作
★★★★★要特別注意 ★★★★★
在輸出成 Lottie 動畫檔,一定要勾選掉 Glyphs ,移掉原有的字型,不然會一直匯出錯誤( Character could not be created ),也不會將文字輸出成 html。
我們預期透過 Javascript ,動態去替換掉 Lottie 動畫裡先前指定 id 的文字圖層,這邊以vue 程式碼為例:
撰寫 Example.vue
<template>
<div>
<div class="flex">
<div ref="monkey" />
</div>
</div>
</template>
<script>
import loApi from 'lottie-api'
import lottie from 'lottie-web'
import { numberFormat } from '@/utils'
export default {
components: {
},
data() {
return {
lottieAnimation: null
}
},
created() {
},
mounted() {
this.lottieAnimation = this.loadLottieAnimation()
let count = 1
const that = this
// 每兩秒去修改 rate 裡面的值
setInterval(() => {
count = count + 0.01
var api = loApi.createAnimationApi(that.lottieAnimation)
var elements = api.getKeyPath('test#rate').getElements() // 查找對象
var ele = elements[0]
const result = '' + numberFormat(count, 2) // 修改改傳入的值必須是字元串不能是數字,否則會失敗
ele.setText(result)
}, 2000)
},
methods: {
loadLottieAnimation() {
return lottie.loadAnimation({
container: this.$refs.monkey, // 掛在到對應的 DOM 節點
loop: true,
animationData: require('@/assets/lottie/monkey.json'),
autoplay: true
})
}
}
}
</script>
完成結果
結論
Adobe After Effect 本身可透過 Lottie Api 達到前端和動畫做互動,對於撰寫小遊戲真的相當的方便,提供相當多事件及屬性可以調整,像是速度、播放次數、重覆播放,播放完成執行事件等等。