mpvue動畫

記錄一下用mpvue開發微信小程序遇到的問題
背景是小程序上需要寫一個簡單的循環動畫,試了幾種方法,留下了一堆坑,之后如果有空或者又遇到這個問題了再填吧(跑)

1.wx.createAnimation

先調用createAnimation API創建一個動畫實例animation。調用實例的方法來描述動畫。最后通過動畫實例的export方法導出動畫數據傳遞給組件的 animation 屬性。官方文檔的例子如下:

<view animation="{{animationData}}" style="background:red;height:100rpx;width:100rpx"></view>
Page({
  data: {
      animationData: {}
    },
  onShow: function () {
    var animation = wx.createAnimation({
        duration: 1000,
        timingFunction: 'ease',
      })

      this.animation = animation

      animation.scale(2,2).rotate(45).step()

      this.setData({
        animationData:animation.export()
      })

      setTimeout(function() {
        animation.translate(30).step()
        this.setData({
          animationData:animation.export()
        })
      }.bind(this), 1000)
  }
})

mpvue和小程序原生的寫法稍微有點不同:

<div :animation="animationData"></div>
const app = new Vue({
  data: {
      animationData: {}
    },
  onShow () {
    let animation = mpvue.createAnimation({
        duration: 1000,
        timingFunction: 'ease',
      })

    animation.scale(2,2).rotate(45).step()

    this.animationData = animation.export()
  }
})

大體上都是相同的,不一樣的地方在于mpvue沒有this.animation,因為原生的小程序this指的是最外面的Page,而mpvue中this指的是外層vue對象,兩者雖然看起來一樣,但是指向不同,編譯以后會報錯(暫時沒有解決mpvue中不能使用微信小程序的this.animation的問題,這個坑,之后有空再填orz),但是可以直接把創建的動畫實例animation賦值給已經綁定在動畫節點上的this.animationData,就可以該元素的動畫效果了,我暫時沒有搞明白為什么原生小程序還需要給this.animation賦值一個動畫實例,明明可以直接給綁定在動畫節點上的變量賦值實現動畫效果(留個坑)

2.關鍵幀動畫

從小程序基礎庫2.9.0開始支持一種更友好的動畫創建方式,用于代替舊的wx.createAnimation。它具有更好的性能和更可控的接口。在頁面或自定義組件中,當需要進行關鍵幀動畫時,可以使用 this.animate 接口:

this.animate(selector, keyframes, duration, callback)

參數列表如下:

  • selector 選擇器
  • keyframes 關鍵幀信息
  • duration 動畫持續時長(毫秒為單位)
  • callback 動畫完成后的回調函數
    之前已經說了,在mpvue里面的this和原生小程序中的this不同,所以就不能直接使用this.animate接口(暫時不知道怎么在mpvue中直接使用this.animate接口,留個坑)
    舉個在原生小程序里使用的例子:
<div id="container"></div>
Page({
  data: {
      animationData: {}
    },
  onShow: function() {
    this.animate('#container', [
      { opacity: 1.0, rotate: 0, backgroundColor: '#FF0000' },
      { opacity: 0.5, rotate: 45, backgroundColor: '#00FF00'},
      { opacity: 0.0, rotate: 90, backgroundColor: '#FF0000' },
      ], 5000, function () {
        this.clearAnimation('#container', { opacity: true, rotate: true }, function () {
          console.log("清除了#container上的opacity和rotate屬性")
        })
    }.bind(this))
  }
})

調用animate API 后會在節點上新增一些樣式屬性覆蓋掉原有的對應樣式。如果需要清除這些樣式,可在該節點上的動畫全部執行完畢后,在回調函數中使用this.clearAnimation清除這些屬性。

3.css3動畫

看了一圈發現原生小程序的動畫對mpvue不是很友好,而且只能執行一次,要想循環還需要寫定時器,所以還可以直接選擇用css3動畫來寫:

div {
  animation: animation 1s;
}
@keyframes animation {
  from {background: red;}
  to {background: yellow;}
}

OK,一下子就搞定了

看了看文檔,寫完以后還是對小程序動畫一知半解,留下了不少坑沒有解決,希望之后會把這些坑補上orz。如果上面有什么寫的不對的地方或者想法可以指正

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容