教程 animejs tutorial

使用 timeline 创建序列动画

Anime.js 的 timeline 允许你将多个动画组合在一起,形成复杂的序列动画,支持同步、延迟和重叠效果。

创建 timeline

使用 anime.timeline() 创建时间轴实例:

js
const tl = anime.timeline({
  easing: "easeOutExpo",
  duration: 750,
});

添加动画

通过 add() 方法向时间轴中添加动画:

js
tl.add({
  targets: ".box1",
  translateX: 250,
}).add(
  {
    targets: ".box2",
    translateX: 250,
  },
  "-=500"
); // 500ms 前开始,即两个动画部分重叠

时间轴控制

时间轴支持暂停、播放、倒放等控制:

js
tl.pause();
tl.play();
tl.reverse();

小结

timeline 是实现复杂动画序列的利器,帮助你轻松构建协调的动画效果。

示例演示

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

<head> <meta charset="UTF-8" /> <title>Anime.js Timeline 示例</title> <style> .box1, .box2 { width: 60px; height: 60px; background-color: #4FC08D; margin: 10px; display: inline-block; border-radius: 6px; user-select: none; }

.box2 {
  background-color: #F67280;
}

#startBtn {
  display: block;
  margin: 20px auto;
  padding: 8px 16px;
  font-size: 16px;
  cursor: pointer;
  border-radius: 6px;
  border: none;
  background-color: #4FC08D;
  color: white;
  transition: background-color 0.3s;
}

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

</style> </head>

<body> <div class="box1"></div> <div class="box2"></div> <button id="startBtn">点击开始动画</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js&quot;&gt;&lt;/script&gt; <script> var tl = anime.timeline({ easing: ‘easeOutExpo’, duration: 750, autoplay: false // 关闭自动播放 });

tl
  .add({
    targets: '.box1',
    translateX: 250
  })
  .add({
    targets: '.box2',
    translateX: 250
  }, '-=500');

document.getElementById('startBtn').onclick = function () {
  tl.restart();  // 重启并播放动画
};

</script> </body>

</html>