1. 程式人生 > >微信小程式:動畫(Animation)

微信小程式:動畫(Animation)

簡單總結一下微信動畫的實現及執行步驟。

一、實現方式

官方文件是這樣說的:①建立一個動畫例項 animation。②呼叫例項的方法來描述動畫。③最後通過動畫例項的 export 方法匯出動畫資料傳遞給元件的 animation 屬性。

因為小程式是資料驅動的,給這句話加上數字標註分為三步:

前兩步是定義一個動畫並設定都要幹什麼,然後把這個設定好的“規則”扔給介面上的某個元素,讓它按照這個規則執行。

當然如果有多個元素的animation="{{ani}}",也都會執行這個動畫規則。

二、用例子說話

新建一個小程式,把沒用的刪掉修改一下,做個簡單例子,上圖

程式碼如下:

index.wxml,一個helloworld,一個按鈕
<view class="container">
  <view class="usermotto" animation="{{ani}}">
    <text class="user-motto">{{motto}}</text>
  </view>
  <button bindtap='start'>動畫</button>
</view>
index.wxss, 為了看著方便加了個邊框
.usermotto {
  margin-top: 100px;
  border: solid;
}

index.js

Page({
  data: {
    motto: 'Hello World',
  },
  start:function(){
    var animation = wx.createAnimation({
      duration: 4000,
      timingFunction: 'ease',
      delay: 1000
    });
    animation.opacity(0.2).translate(100, -100).step()
    this.setData({
      ani:  animation.export()
    })
  }
})

 三、相關引數及方法

簡單介紹一下例子中的幾個引數和方法(其他的詳見官方文件):

      duration: 動畫持續多少毫秒      timingFunction: “運動”的方式,例子中的 'ease'代表動畫以低速開始,然後加快,在結束前變慢        delay: 多久後動畫開始執行

      opacity(0.2) 慢慢變透明

      translate(100, -100) 向X軸移動100的同時向Y軸移動-100

      step(): 一組動畫完成,例如想讓上例中的HelloWorld向右上方移動並變透明後,再次向左移動50可以繼續寫 animation.translateX( -50).step() , 作用就是向右上方移動和變透明是同時進行, 這兩種變化完成之後才會進行向左執行的一步。