首页 > 解决方案 > 使用 translateX 优化 CSS 动画的 CPU 使用率

问题描述

我正在制作一些愚蠢的小动画。首先,我用 JavaScript 制作动画,可以预见它的性能很糟糕。然后我尝试用 CSS 动画重现它,认为这样会使用更少的 CPU。它的性能确实更好,但它仍然使用比我想要的更多的 CPU。所以我的问题是,有人对如何最有效地实现这个简单的动画有任何想法吗?

const bars = document.getElementById("top").children;

const colorMap = {
  0: 3,
  1: 4,
  2: 5,
  3: 0,
  4: 1,
  5: 2,
};
const getDuration = () => 1000 + Math.random() * 4000;
function makeBubble(bar, i) {
  const bubble = document.createElement("div");

  bubble.style.animationDuration = `${getDuration()}ms`;
  bubble.classList.add("bubble");
  bubble.classList.add(`top-${colorMap[i]}`);

  bubble.addEventListener("animationend", () => {
    bar.removeChild(bubble);
    makeBubble(bar, i);
  });

  bar.appendChild(bubble);
}

// Initialize bubbles
for (let i = 0; i < bars.length; i++) {
  makeBubble(bars[i], i);
}
#top div {
  height: 0.75em;
  display: flex;
  align-items: center;
}
#top .top-0 {
  background-color: #4c22c8
}
#top .top-1 {
  background-color: #6c49d1
}
#top .top-2 {
  background-color: #8b70da
}
#top .top-3 {
  background-color: #aa97e3
}
#top .top-4 {
  background-color: #cabeec
}
#top .top-5 {
  background-color: #e9e5f5
}
@keyframes move-bubble {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(100vw);
  }
}
#top .bubble {
  border-radius: 50%;
  height: 4px;
  width: 4px;
  animation-timing-function: cubic-bezier(0.5, 0.0, 1, 0.75);
  animation-name: move-bubble;
}
<div id="top">
  <div class="top-0"></div>
  <div class="top-1"></div>
  <div class="top-2"></div>
  <div class="top-3"></div>
  <div class="top-4"></div>
  <div class="top-5"></div>
</div>

标签: javascriptcsscss-animations

解决方案


推荐阅读