我想问一下,这段CSS代码有什么问题吗?它用于动画背景图像 - 缩放效果。
@media (min-width: 1000px) {
.anim-on {
background-size: 110% 110%;
background-position: center center;
animation: shrink 12s infinite alternate;
}
.anim-out {
background-size: 120% 120%;
background-position: center center;
animation: small 6s infinite alternate;
}
@keyframes shrink {
0% {
background-size: 110% 110%;
}
100% {
background-size: 100% 100%;
}
}
@keyframes small {
0% {
background-size: 100% 100%;
}
100% {
background-size: 110% 110%;
}
}
}
这段代码产生了很好的效果,但我看到,在较慢的机器上,效果很差。
怎么了?或者也许有人有更好的想法,如何以更好的技术创造这种效果?
最佳答案
背景大小是一个视觉属性,因此对其值的任何更改都会导致重新绘制。绘画是一项非常昂贵的操作,必然会对低端机器的性能产生影响。克服这个问题的一种方法是使用 CSS transform
(准确地说是缩放)而不是 background-size
change 来制作动画。
会造成性能影响的代码段:
下面的代码片段使用了与问题中相同的动画。当您运行此代码段并使用 Chrome 开发工具检查它时(通过启用“Show Paint Rects”选项),您会看到两个图像都有一个与之关联的绘画矩形(绿色或红色框)并且动画是盒子一直闪烁(或保持原样)。这表明重绘经常发生,因此会影响性能。
.anim-on,
.anim-out {
height: 200px;
width: 200px;
background: url(http://lorempixel.com/200/200/nature/1);
}
.anim-on {
background-size: 110% 110%;
background-position: center center;
animation: shrink 12s infinite alternate;
}
.anim-out {
background-size: 120% 120%;
background-position: center center;
animation: small 6s infinite alternate;
}
@keyframes shrink {
0% {
background-size: 110% 110%;
}
100% {
background-size: 100% 100%;
}
}
@keyframes small {
0% {
background-size: 100% 100%;
}
100% {
background-size: 110% 110%;
}
}
/* Just for demo */
div {
float: left;
margin-right: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<div class='anim-on'></div>
<div class='anim-out'></div>
对性能影响较小的代码段:
在下面的代码片段中,我将 background-image
添加到伪元素,然后对其使用 scale
变换以产生放大/缩小效果.父级的 overflow: hidden
设置可防止动画影响其大小。如果您使用 Chrome 开发工具对此进行检查,您会看到绿色或红色框仅在页面加载并消失时出现一次。这表明在动画本身期间没有进一步的重绘发生,因此从性能的 Angular 来看它更好。您还会注意到此动画比之前的动画更流畅。
.anim-on,
.anim-out {
position: relative;
height: 200px;
width: 200px;
overflow: hidden;
}
.anim-on:after,
.anim-out:after {
position: absolute;
content: '';
height: 100%;
width: 100%;
top: 0px;
left: 0px;
background: url(http://lorempixel.com/200/200/nature/1);
}
.anim-on:after {
animation: shrink 12s infinite alternate;
}
.anim-out:after {
animation: small 6s infinite alternate;
}
@keyframes shrink {
0% {
transform: scale(1.1);
}
100% {
transform: scale(1);
}
}
@keyframes small {
0% {
transform: scale(1);
}
100% {
transform: scale(1.1);
}
}
/* Just for demo */
div {
float: left;
margin-right: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<div class='anim-on'></div>
<div class='anim-out'></div>
您可以在 CSS Triggers website 中找到有关各种 CSS 属性以及更改它们的值将如何影响渲染过程的更多信息。 .
您可以在以下文章/网站中找到有关渲染过程以及使用 transform
(相对于其他一些属性)如何提高性能的更多信息:
关于html - Css 动画 - 动画缓慢且抖动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34311417/