教程 animejs tutorial

动画控制函数

Anime.js 提供多种动画控制函数,允许你在运行时对动画进行暂停、播放、重启和反转等操作,增强动画的交互性。

常用控制函数

  • play() — 播放动画,如果已暂停则继续播放
  • pause() — 暂停动画
  • restart() — 从头重新开始动画
  • reverse() — 反转动画播放方向
  • seek(time) — 跳转动画到指定时间点(毫秒)

示例代码

js
const animation = anime({
  targets: ".box",
  translateX: 250,
  duration: 2000,
  autoplay: false,
});

// 播放动画
animation.play();

// 暂停动画
// animation.pause();

// 反转动画
// animation.reverse();

// 重新开始动画
// animation.restart();

事件监听与控制结合

可以结合事件监听回调,动态控制动画状态。

小结

熟悉动画控制函数后,可以根据交互需求随时调整动画播放状态,提升用户体验。

示例演示

在线代码演示
源码
<!DOCTYPE html>
<html lang="zh">

<head> <meta charset="UTF-8" /> <title>Anime.js 动画控制函数示例</title> <style> .box { width: 80px; height: 80px; background: #4FC08D; margin: 40px auto; border-radius: 10px; line-height: 80px; text-align: center; color: white; font-weight: bold; user-select: none; }

button {
  margin: 5px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  border-radius: 4px;
  border: none;
  background-color: #4FC08D;
  color: white;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #3a9d6f;
}

</style> </head>

<body> <div class="box">Box</div> <div style="text-align:center;"> <button id="playBtn">播放</button> <button id="pauseBtn">暂停</button> <button id="reverseBtn">反转</button> <button id="restartBtn">重启</button> </div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js&quot;&gt;&lt;/script&gt; <script> var animation = anime({ targets: ‘.box’, translateX: 300, duration: 3000, autoplay: false, easing: ‘easeInOutSine’ });

document.getElementById('playBtn').onclick = function () { animation.play(); };
document.getElementById('pauseBtn').onclick = function () { animation.pause(); };
document.getElementById('reverseBtn').onclick = function () { animation.reverse(); };
document.getElementById('restartBtn').onclick = function () { animation.restart(); };

</script> </body>

</html>