教程 animejs tutorial

如何封装与扩展

在实际项目中,封装动画逻辑可以提升代码复用性和维护性。扩展动画则可实现更丰富的效果。

1. 封装动画函数

将动画配置封装为函数,方便多处调用和参数复用。

js
function createSlideAnimation(target, distance, duration = 1000) {
  return anime({
    targets: target,
    translateX: distance,
    duration: duration,
    easing: "easeInOutQuad",
  });
}

调用:

js
const animation = createSlideAnimation(".box", 250);
animation.play();

2. 利用 Promise 处理动画顺序

封装函数返回 Promise,方便链式调用。

js
function slide(target, distance) {
  return anime({
    targets: target,
    translateX: distance,
    duration: 800,
    easing: "easeOutExpo",
  }).finished;
}

// 使用 async/await 顺序执行
async function runAnimations() {
  await slide(".box1", 200);
  await slide(".box2", 200);
}
runAnimations();

3. 扩展动画效果

通过自定义动画属性或结合其它库,实现个性化效果。

示例演示

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

<head> <meta charset="UTF-8" /> <title>封装与扩展示例</title> <style> body { font-family: Arial, sans-serif; padding: 40px; background: #f5f5f5; text-align: center; }

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

button {
  padding: 12px 24px;
  font-size: 16px;
  cursor: pointer;
  border: none;
  background-color: #4FC08D;
  color: white;
  border-radius: 6px;
  margin-top: 30px;
  transition: background-color 0.3s;
}

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

</style> </head>

<body>

<div class="box"></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> (function () { const box = document.querySelector(‘.box’); const btn = document.getElementById(‘startBtn’);

  function createSlideAnimation(target, distance, duration = 1000) {
    return anime({
      targets: target,
      translateX: distance,
      duration: duration,
      easing: 'easeInOutQuad',
      autoplay: false
    });
  }

  function slide(target, distance) {
    return anime({
      targets: target,
      translateX: distance,
      duration: 800,
      easing: 'easeOutExpo'
    }).finished;
  }

  btn.addEventListener('click', async () =&gt; {
    // 封装的动画实例
    const anim = createSlideAnimation(box, 250);
    anim.play();

    // 等待动画完成后,继续执行异步链式动画
    await slide(box, 0);
    await slide(box, 250);
  });
})();

</script>

</body>

</html>