微信小程序可实时改变转速的css3旋转动画

WXML

<view class=box style=background-color:{
         
  {backgroundcolor}}>
</view>
<view class=viewBox>
  <button bindtap=changeColor data-color=black class=box>黑</button>
  <button bindtap=changeColor data-color=violet class=box>紫</button>
  <button bindtap=changeColor data-color=orange class=box>橙</button>
  <button bindtap=changeColor data-color=blue class=box>蓝</button>
  <button bindtap=changeColor data-color=green class=box>绿</button>
</view>

JS

data: {
    backgroundcolor:red
  },
  changeColor:function(e){
    this.setData({
      backgroundcolor: e.currentTarget.dataset.color
    })
  }
那么下面咱们说一说这个旋转的动画。小程序里呢,有自己的动画api,但是用起来感觉极其麻烦,而且容易产生倒转,对设备的性能消耗也多,动画多了以后就会极其卡顿,所以还是css3的动画比较好。

首先来写这个css3动画

css3旋转动画

<view class=animationSlow></view>
.animationSlow {
   width: 100rpx;
  height: 100rpx;
  background-color: orange;
  animation-name: myfirst; /*动画的名称 */
  animation-duration: 2000ms; /*动画从开始到结束的时间*/
  animation-timing-function: linear; /*动画执行快慢的参数*/
  animation-iteration-count: infinite; /*动画执行多少次的参数*//*以下是兼容ios所需,参数意义与上相同*/
  -webkit-animation-name: myfirst;
  -webkit-animation-duration: 2000ms;
  -webkit-animation-timing-function: linear;
  -webkit-animation-iteration-count: infinite;
}
@keyframes myfirst {
  /*开始转的角度*/
  from {
    transform: rotate(0deg);
  }/*结束的角度*/
  to {
    transform: rotate(360deg);
  }
}
/*兼容ios*/
@-webkit-keyframes myfirst {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
<view class=animationSlow style=animation-duration: 2000ms;-webkit-animation-duration: 2000ms;></view>

2.在页面对应的js中,设置掌控时间的Page.data属性,将wxml里内联属性的时间改为Page.data的属性。

data: {
    animationTime:2000ms
  },
<view class=animationSlow style=animation-duration: {
         
  {animationTime}};-webkit-animation-duration: {
         
  {animationTime}};></view>

解决IOS系统的BUG

上面说了,IOS系统上呢,动画一旦开始,这个方法就不能用了。那么咱是不是可以先把这个动画停下来,然后再改转速呢?这个办法可不可以呢?答案是肯定的,但是不是去把动画时间改为0,而是采用了css3动画的一个属性。

animation-play-state: paused|running;

简而言之就是先用这个属性把动画暂停,修改转速,然后再让它跑起来。这一切都得再js里进行。 1.需要在标签的内联样式里加上这个属性,在Page.data里再定义一个属性控制开始暂停。

<view class=animationSlow style=animation-duration: {
         
  {animationTime}};-webkit-animation-duration: {
         
  {animationTime}};animation-play-state:{
         
  {status}};-webkit-animation-play-state:{
         
  {status}};></view>
data: {
    animationTime:2000ms,
    status: running//paused
  },

2.然后我们去修改改变转速的方法。暂停>(修改>跑起来),效果上稍微有些延迟。

changeTime:function(e){
    this.setData({
      status: paused
    })
    this.setData({
      timeAnimation: e.currentTarget.dataset.time,
      status: running
    })
  },

本次分享结束(@LcFireRabbit) 欢迎指导

经验分享 程序员 微信小程序 职场和发展