简单动画播放/倒放按钮

3

尝试使用animate.js框架播放在正向和反向播放之间切换的动画。

HTML

<button class="btn">PLAY</button>
<div class="square"></div>

JS

/** animation */
let animeSquare = anime({
  targets: '.square',
  translateX: '100px',
  duration: 500,
  autoplay: false,
});


/** button */
$('.btn').click(function() {
  if ($(this).hasClass('is-active')) {
    animeSquare.reverse();
    $(this).removeClass('is-active');
  } else {
    animeSquare.play();
    $(this).addClass('is-active');
  }
});

问题是我必须点击两次按钮才能播放动画,为什么呢?
Codepen: https://codepen.io/aitormendez/pen/ymyzoq
3个回答

1
动漫插件具有以下功能: 此外,由于没有循环,每次都需要重新启动。
因此,您的代码可以简化为:

let animeSquare = anime({
    targets: '.square',

    direction: 'normal',  // normal or reverse????

    /** Properties to animate */
    translateX: '100px',

    /** Animation settings */
    duration: 500,
    autoplay: false,

    begin: function (anim) {

    },
    complete: function (anim) {
        // change direction..... so the next time you play....
        anim.direction = (anim.direction == 'normal') ? 'reverse' : 'normal';
    }
});

$('.btn').click(function () {
    animeSquare.restart();
});
.square {
    width: 100px;
    height: 100px;
    background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.2.0/anime.min.js"></script>


<button class="btn">PLAY</button>
<div class="square"></div>


1
我注意到以下逻辑:在第一次播放时,您使用animeSquare.play();,但从第二次开始,您需要使用animeSquare.reverse();将动画反转,然后在反转后使用animeSquare.play();播放动画。

let animeSquare = anime({
  targets: '.square',

  /** Properties to animate */
  translateX: '100px',

  /** Animation settings */
  duration: 500,
  autoplay: false,
});
var c=0;
$('.btn').click(function() {
  if(c==0){
    animeSquare.play();
    c++;
  }else{
    
    animeSquare.reverse();
    animeSquare.play();
    
  }
  
  console.log(animeSquare);
});
.square {
  width: 100px;
  height: 100px;
  background-color: red;
}
<button class="btn">PLAY</button>
<div class="square"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.2.0/anime.min.js"></script>


1
我尝试的代码是:

let animeSquare = anime({
  targets: '.square',

  /** Properties to animate */
  translateX: '100px',

  /** Animation settings */
  duration: 500,
  autoplay: false,
});

$('.btn').click(function() {
  if ($(this).hasClass('is-active')) {
    animeSquare.direction = "reverse"
    animeSquare.play();
    $(this).removeClass('is-active');
  } else {
    animeSquare.direction = "normal"
    animeSquare.play();
    $(this).addClass('is-active');
  }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接