微信小程序 旋转图片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;
}

猜你喜欢

转载自www.cnblogs.com/zhangzheng022/p/11275349.html
今日推荐