需要在身体中创建线性渐变动画,但它使用了大量的cpu,这导致风扇运行的声音很大。
我找到了这个解决方案animated linear gradient devouring CPU usage
这个技巧将cpu使用率降低到3-5%,这是很棒的。但是当你调整窗口大小时,它会在后台产生一个bug。
我尝试创建resize函数,因为我猜当你调整窗口大小时,width属性会改变,这会导致bug。但这并没有起作用。
[Codepen](https://codepen.io/iclassici/pen/poPXRyp)发布于 2021-08-18 09:35:13
在做:
body.classList.remove('bg');
body.classList.add('bg');实际上什么都没有发生,因为类在系统有机会重新计算/重画东西之前就被恢复了。
您需要像删除类一样删除该类,然后在恢复它之前等待。尝试使用setTimeout或requestAnimationFrame。
如果你能把你的代码做成一个代码片段,我们可以在你的问题中运行,这将帮助我们测试东西并给出一个更完整的答案。
更新:采用代码描述中给出的代码,此代码片段对resize函数进行了更改,删除了bganimation类,设置了较短的超时时间,并恢复了该类。这确保了系统将重置它提供给GPU的任何参数。
注意:在我功能相当强大的笔记本电脑Windows10上,背景动画只占用了不到2%的CPU和大约20%的GPU。
window.addEventListener("resize", myFunction);
function myFunction() {
body = document.getElementsByTagName('body')[0];
body.classList.remove('bganimation');
setTimeout(function() {
body.classList.add('bganimation');
}, 100);
}.bg {
width: 100vw;
height: 100vh;
}
.bg::before {
content: '';
position: fixed;
z-index: -2;
top: 0;
left: 0;
width: 600%;
height: 100%;
bottom: 0;
background: linear-gradient(45deg, #F17C58, #E94584, #24AADB, #27DBB1, #FFDC18, #FF3706);
background-size: 100% 100vh;
background-repeat: no-repeat no-repeat;
background-position: left top;
}
.bganimation {
animation: gradient 16s linear infinite alternate;
}
@keyframes gradient {
0% {
transform: translateX(0);
}
100% {
transform: translateX(-400vw);
/* 5/6x100% */
}
}<body class="bg bganimation">
</body>
https://stackoverflow.com/questions/68828949
复制相似问题