uni.createAnimation(OBJECT)
官方是這么描述animation動(dòng)畫的過程:
創(chuàng)建一個(gè)動(dòng)畫實(shí)例 animation或链。調(diào)用實(shí)例的方法來描述動(dòng)畫趟庄。最后通過動(dòng)畫實(shí)例的export方法導(dǎo)出動(dòng)畫數(shù)據(jù)傳遞給組件的animation屬性弃揽。
接下來我就一一說明
如何使用uniapp動(dòng)畫
先說需求, 點(diǎn)擊按鈕小貓開始運(yùn)動(dòng)
image
首先在元素上綁定動(dòng)畫(
:animation="animationData"
)
<view :animation="animationData" class="animation">
<image src="../../static/貓.png"></image>
</view>
<button @click="running" >別跑</button>
這一步是把a(bǔ)nimationData數(shù)據(jù)傳遞給animation屬性
export default {
data() {
return {
animationData: {}
// 在data中初始化animationData
}
},
onUnload() {
this.animationData = {}
// 頁面關(guān)閉后清空數(shù)據(jù)
},
onload(){
this.animation = uni.createAnimation()
// 創(chuàng)建動(dòng)畫實(shí)例
},
methods: {
running() {
this.animation.translateX(500).step({duration:1000})
// 調(diào)用實(shí)例的方法來描述動(dòng)畫,translateX定義動(dòng)畫類型為x軸偏移, 500為偏移長(zhǎng)度, 單位px
// 調(diào)用 step() 來表示一組動(dòng)畫完成(當(dāng)前參數(shù)動(dòng)畫時(shí)間1s)
// step 可以配置參數(shù)用于指定當(dāng)前組動(dòng)畫的配置庸追。具體參數(shù)請(qǐng)看文檔
this.animationData = this.animation.export()
// export方法導(dǎo)出動(dòng)畫數(shù)據(jù)
}
}
}
一個(gè)動(dòng)畫就定義好了
下面來看效果
image
總結(jié)一下
image
鏈?zhǔn)絼?dòng)畫
可以在step()之后緊接第二個(gè)動(dòng)畫, 類似promise寫法
this.animation.translateX(100).step()
.translateY(100).step()
.translateX(0).step()
.translateY(0).step()
效果
image
動(dòng)畫多次觸發(fā)
如果動(dòng)畫完成后, 元素未回到初始位置, 第二次動(dòng)畫是無法觸發(fā)的
有兩種方法使元素回到原位
通過鏈?zhǔn)讲僮?/h4>
在動(dòng)畫最后在添加一個(gè)動(dòng)畫的, 效果是返回原位(動(dòng)畫時(shí)間是0)
this.animation.translateX(200).step({duration:700})
.translateX(0).opacity(0).step({duration:0})
設(shè)置timeout
如果動(dòng)畫時(shí)間是0.7s, 那就在0.8s之后使用動(dòng)畫讓元素返回
timeout調(diào)用時(shí)間在動(dòng)畫完成之后
同樣duration為0
running() {
this.animation = uni.createAnimation()
this.animation.translateX(200).step({duration:700})
this.animationData = this.animation.export()
setTimeout(()=>{
this.animation.translateX(0).opacity(0).step({duration:0})
this.animationData = this.animation.export()
}, 800);
}
效果
image