在阅读了一篇关于CSS animations and how to build them的文章后,我构建了自己的CSS动画,并试图提高CSS动画的性能,我的动画由三个HTML元素组成,它们改变宽度以指示媒体正在播放。
在ChromeDevtools中检查时间轴和资源选项卡时,我发现动画会导致高CPU负载。
如何将动画转换为GPU硬件加速,而不是浏览器渲染器,这会导致高CPU负载?我读到过您可以使用硬件加速来强制动画在GPU上运行。
- 有没有办法把这个(动画条的宽度)转换成GPU层?我能翻译一下吗?或者有更好的方法?*
有3个小节。这是它的动画,不是样式。
@keyframes music {
0% { width:17px; }
10% { width:11px; }
20% { width:37px; }
30% { width:30px; }
40% { width:15px; }
50% { width:10px; }
60% { width:24px; }
70% { width:17px; }
80% { width:21px; }
90% { width:32px; }
100% { width:17px; }
}
.lines-ani {
transform: rotateY(180deg);
}
.lines-ani .lines {
animation: music 1.5s 2s ease-out alternate infinite;
}
.lines-ani .lines:before {
animation: music 1.5s 1.5s ease-out alternate infinite;
}
.lines-ani .lines:after {
animation: music 1.5s 2.5s ease-out alternate infinite;
}
1条答案
按热度按时间kse8i1jr1#
如果你想避免重画,并将动画移动到GPU,那么你可以使用3D转换来产生效果,而不是动画
width
。如this article中所述,使用3D转换意味着浏览器将使动画GPU加速。CSS动画、转换和过渡不会自动由GPU加速,而是由浏览器较慢的软件渲染引擎执行。那么到底是什么迫使浏览器切换到GPU模式呢?许多浏览器通过特定的CSS规则提供GPU加速。
目前,Chrome、FireFox、Safari、IE9+和最新版本的Opera等浏览器都配备了硬件加速功能;他们只在有迹象表明DOM元素将从中受益时才使用它。对于CSS,最强的迹象是3D转换正在应用于元素。
将动画转换为3D变换本身并不是一个很大的过程,所需要的只是在所有三个元素上设置一个初始的
width
,并根据设置的初始宽度将@keyframes
规则中的width
转换为相应的比率值。一个宽度动画通常就是
scaleX
,但是我们使用了scale3d
,因为我们需要将动画移动到GPU上。由于scale3d
有3个参数(用于三个轴中的每一个轴的缩放),我们可以提供1(初始缩放)作为其他两个轴的值。例如,所提供的
10%
帧具有width: 11px
设置,下面是我们如何获得其等效的scale3d
值:width
。在下面的代码片段中,我将其设置为17px。scale3d(0.64, 1, 1)
。scale3d
,你也可以使用scaleX() translateZ(0)
。translateZ(0)
是一个3D变换,整个变换仍然会产生相同的效果。