微信小程序 旋轉圖片Animation


最近制作TODO小程序想旋轉圖片來達到一秒走一下

首先在wxml定義一個圖形

<view class="container">
  <view class="page-body">
    <view class="page-section">
      <view class="animation-element-wrapper">
        <view class="animation-element" animation="{{animation}}"></view>
      </view>
      <view class="animation-buttons" scroll-y="true">
        <button class="animation-button" bindtap="startAnimationInterval">旋轉</button>
        <button class="animation-button" bindtap="stopAnimationInterval">暫停</button>
        <button class="animation-button" bingtap=""></button>
        <button class="animation-button animation-button-reset" bindtap="reset">還原</button>
      </view>
    </view>
  </view>
</view>

{{animation}}是在js定義的data

data: {
    animation: ''
  }

相關js代碼

var _animation; // 動畫實體
var _animationIndex = 0; // 動畫執行次數index(當前執行了多少次)
var _animationIntervalId = -1; // 動畫定時任務id,通過setInterval來達到無限旋轉,記錄id,用於結束定時任務
const _ANIMATION_TIME = 60; // 動畫播放一次的時長ms
Page({
  data: {
    animation: ''
  },
  onReady: function () {
    _animationIndex = 0;
    _animationIntervalId = -1;
    this.data.animation = '';
  },

  onShow: function () {
    _animation = wx.createAnimation({
      duration: _ANIMATION_TIME,
      timingFunction: 'linear', // "linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end"
      delay: 0,
      transformOrigin: '50% 50% 0'
    })
  },

  /**
   * 實現image旋轉動畫,每次旋轉 1 * n度
   */
  rotateAni: function (n) {
    _animation.rotate(1 * (n)).step()
    this.setData({
      animation: _animation.export()
    })
  },

  /**
   * 開始旋轉
   */
  startAnimationInterval: function () {
    var that = this;
    that.rotateAni(++_animationIndex); // 進行一次旋轉
    _animationIntervalId = setInterval(function () {
      that.rotateAni(++_animationIndex);
    }, _ANIMATION_TIME); // 每間隔_ANIMATION_TIME進行一次旋轉
  },

  /**
   * 停止旋轉
   */
  stopAnimationInterval: function () {
    if (_animationIntervalId > 0) {
      clearInterval(_animationIntervalId);
      _animationIntervalId = 0;
    }
  },
})

css

.animation-element-wrapper {
  display: flex;
  width: 100%;
  padding-top: 150rpx;
  padding-bottom: 150rpx;
  justify-content: center;
  overflow: hidden;
  background-color: #ffffff;
}
.animation-element {
  width: 200rpx;
  height: 200rpx;
  background-color: #1AAD19;
}
.animation-buttons {
  padding: 30rpx 50rpx 10rpx;
  width: 100%;
  height: 700rpx;
  box-sizing: border-box;
}
.animation-button {
  float: left;
  line-height: 2;
  width: 300rpx;
  margin: 15rpx 12rpx;
}

.animation-button-reset {
  width: 620rpx;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM