javascript - 使用 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>
解决方案
推荐阅读
- mapbox - 如何在布局中使用 maki 图标:{ }
- power-automate - 在 Power Automate 中,如何筛选列表并保存结果?
- docker - 如何使用 Docker 和文本编辑器在主机上创建文件以进行本地开发(权限问题)
- python-3.x - flake8:F821 全局变量的未定义名称
- scala - 小猫 - 模棱两可的进口(再次)
- html - 如何在选中复选框时为复选框添加边框?
- database - 努力找出多种关系的数据库结构
- ruby-on-rails - 测试 Sidekiq Web UI 时出现 Redis::CannotConnectError
- ios - Xcode 故事板屏幕类型影响模拟器中的布局
- c# - 如何更改粒子效果颜色?