教程 animejs tutorial

调试技巧

动画调试能帮助你快速定位问题,优化动画效果。下面介绍几种实用的方法:

1. 利用回调函数打印动画进度

Anime.js 提供了多种回调函数,如 begin、update、complete,可在其中打印动画状态。

js
anime({
  targets: ".box",
  translateX: 250,
  duration: 1000,
  update: function (anim) {
    console.log("动画进度:", anim.progress.toFixed(2), "%");
  },
});

2. 暂停和恢复动画

动画实例支持 .pause() 和 .play() 方法,方便在调试时控制动画进度。

3. 监控当前所有动画实例

anime.running 数组包含当前所有运行中的动画,便于调试动画状态。

4. 简化动画步骤

将复杂动画拆分为简单步骤,逐步排查问题。

示例演示

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

<head> <meta charset="UTF-8" /> <title>Anime.js 调试示例</title> <style> body { font-family: sans-serif; text-align: center; padding: 40px; background-color: #f0f0f0; }

.box {
  width: 100px;
  height: 100px;
  background-color: #4FC08D;
  margin: 20px auto;
  border-radius: 8px;
  user-select: none;
}

button {
  padding: 10px 20px;
  font-size: 16px;
  margin: 0 10px;
  cursor: pointer;
  border: none;
  border-radius: 6px;
  background-color: #4FC08D;
  color: white;
  transition: background-color 0.3s;
}

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

#progress {
  margin-top: 20px;
  font-weight: bold;
  font-size: 18px;
}

</style> </head>

<body>

<div class="box"></div>

<div> <button id="btnPause">暂停动画</button> <button id="btnPlay">继续动画</button> </div>

<div id="progress">动画进度:0%</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js&quot;&gt;&lt;/script&gt; <script> (function () { var box = document.querySelector(‘.box’); var btnPause = document.getElementById(‘btnPause’); var btnPlay = document.getElementById(‘btnPlay’); var progressText = document.getElementById(‘progress’);

  var animation = anime({
    targets: box,
    translateX: 300,
    duration: 4000,
    easing: 'easeInOutQuad',
    loop: true,
    direction: 'alternate',
    update: function (anim) {
      var progress = anim.progress.toFixed(1);
      progressText.textContent = '动画进度:' + progress + '%';
      console.log('动画进度:', progress + '%');
    },
    begin: function () {
      console.log('动画开始');
    },
    complete: function () {
      console.log('动画完成');
    }
  });

  btnPause.addEventListener('click', function () {
    animation.pause();
    console.log('动画已暂停');
  });

  btnPlay.addEventListener('click', function () {
    animation.play();
    console.log('动画继续播放');
  });
})();

</script> </body>

</html>

说明

  • 动画方块左右往返移动;
  • 页面和控制台实时输出动画进度;
  • “暂停动画”和“继续动画”按钮,方便调试动画播放状态;
  • 使用立即执行函数避免变量污染和重复声明。 rgb(240, 240, 240)rgba(240, 240, 240, 0.75)