鼠标移动时CSS动画渲染占用过高问题排查与优化求助
CSS动画鼠标移动时性能骤降的问题排查与优化需求
现象描述
测试CSS动画性能时发现一个特殊现象:为1000个元素执行基于transform和opacity的动画时,PC端资源占用极低。
但只要持续移动鼠标,资源占用情况就会大幅上升。
唯一变量就是鼠标移动,这些元素没有任何鼠标交互(无JS监听、无CSS hover效果),即使元素滚出视口,高资源占用依然存在,测试时窗口始终处于激活状态。
另外,使用width、height、margin等属性做动画时,无论是否移动鼠标,资源占用都很高。
已尝试的无效优化手段
pointer-events: none(符合预期无效果)will-change- 对比
display: inline-block与position: absolute布局 - 对比
transform与opacity动画 - 对比
translate3d与translate - 测试滚出视口的元素
个人猜测
推测该现象与GPU有关:鼠标移动时会触发CPU参与计算,这也解释了为何依赖CPU计算的属性动画无差异,而GPU加速的属性受影响显著。该现象在Brave和Edge浏览器中已确认,Firefox中似乎也存在类似情况。
核心需求
如何让动画始终保持无鼠标移动时的低占用状态?这些元素从未使用任何鼠标交互,无需响应鼠标操作。
复现代码片段
<style> body { padding-bottom: 150vw; } div { position: absolute; height: 50px; width: 50px; pointer-events: none; will-change: transform; background-color: red; animation: Animation 2s ease infinite; } @keyframes Animation { from { transform: scale(0); } to { transform: scale(1); } } </style> <body></body> <script> const size = 50 + 8 + 8; const count = Math.floor(window.innerWidth / size); [...Array(1000)].forEach((_, i) => { let div = document.createElement('div'); div.style.top = Math.floor(i / count) * size + 'px'; div.style.left = Math.floor(i % count) * size + 'px'; document.body.appendChild(div); }); </script>
内容的提问来源于stack exchange,提问作者Jack
相关产品推荐
相关产品推荐

