
透過 Adobe After Effect 製作 lottie 動畫,並與 Javascript 互動 Part 2 - 進階互動應用
前一篇的文章得知,Adobe After Effect透過將圖層給 “#” 當特殊後缀命名,字元輸出後會 #字之後字元將會轉換成 id,Javascript 透過操作 DOM 就能與動畫溝通。這篇針對一些比較JS 和動畫互動的功能做介紹。
幀數是動畫播放的單位,簡單來說就是每秒播放幾個畫格。
[關於幀數的相關文章]
參考前一篇文章,可以透過 lottie api 的 setText 方法,去變更動畫中的文字。
this.lottieAnimation = lottie.loadAnimation({
container: this.$refs.monkey, // 掛在到對應的 DOM 節點
loop: true,
animationData: require('@/assets/lottie/monkey.json'),
autoplay: true
})
that.lottieAnimation.setSpeed(0.1);
this.lottieAnimation.onComplete = function() { // loop = false 才會被觸發
console.log('complete')
}
this.lottieAnimation.onLoopComplete = function() {
console.log('loopComplete')
}
this.lottieAnimation.addEventListener('enterFrame', () => { // 現在在幀
console.log('現在幀數', that.lottieAnimation.currentFrame)
})
that.lottieAnimation.playSegments([11, 30], true) // 播放,第11到30幀的動畫
that.lottieAnimation.addEventListener('DOMLoaded', () => {
document.getElementById('banana').addEventListener('click', function() {
alert('click')
})
})
Adobe After Effect 並沒有內建太多的網頁互動的指令或腳本,因此不太適合做複雜的互動功能,這邊直接操作 CSS 及 JS 會比較容易。
<style lang="scss">
// 滑動事件
#banana:hover {
filter: drop-shadow(0 0 30px rgb(0, 255, 255));
}
</style>
依據前面幾個效果,己經可以組合成一個小遊戲,開始時固定幀數,播放等待遊戲動畫,直到用戶點擊香蕉後,播放第二段動畫。
Demo 影片連結
<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() {
const that = this
that.lottieAnimation = this.loadLottieAnimation()
that.lottieAnimation.playSegments([0, 10], true) // 開場動畫
that.lottieAnimation.addEventListener('enterFrame', () => { // 現在在幀
console.log('enterFrame', that.lottieAnimation.currentFrame)
})
that.lottieAnimation.addEventListener('DOMLoaded', () => {
document.getElementById('banana').addEventListener('click', function() {
that.lottieAnimation.playSegments([11, 30], true) // 播放 11到30幀的動化 香蕉
})
})
let count = 1
// 每兩秒去修改 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() {
const that = this
return lottie.loadAnimation({
container: this.$refs.monkey, // 掛在到對應的 DOM 節點
loop: true,
animationData: require('@/assets/lottie/monkey.json'),
autoplay: true
})
}
}
}
</script>
<style lang="scss">
// 滑動事件
#banana:hover {
filter: drop-shadow(0 0 30px rgb(0, 255, 255));
}
</style>


Adobe After Effect製作動畫及輕量級小遊戲我覺得還是蠻適合,但若是要製作互動性比較高及複雜的遊戲,我倒覺得沒這麼適合,畢竟是為了動畫而生,對於和前端程式互動,並沒有這麼方便。


