我正在研究一个将图像从开始位置+比例转换到结束位置+比例(即填满屏幕)的组件。这是通过translate
和scale
上的CSS变换动画完成的。
挑战在于,使用object-fit
属性的组件用户可能会更改某些要转换的图像。然而,似乎CSS translate
在翻译期间不保持object-fit
财产。
Codepen示例:https://codepen.io/cathyxz/pen/mXgEMB
我知道我可以在技术上为width
和height
制作动画,但是我想保持与浏览器可以出于性能原因animate cheaply的属性一致,即没有影响布局的东西,这使我们只有位置,旋转,缩放,不透明度。
参考文献:https://www.html5rocks.com/en/tutorials/speed/high-performance-animations/
无论如何,我可以逐渐动画我的过渡到“unrop”图像而不是拉伸它们?
object-fit
在转换之前应用于元素。
无论对象上所有CSS的结果是什么,transform
都会接受它并应用转换。实际上,元素保留在DOM中不受影响。这就是为什么transform
不会触发重绘(并且被认为是高效的)。仅转换其渲染(复合层)。由于变换,它的渲染在X轴上被拉伸了4次。但这并没有使元素宽4倍,因此对象适合不能像你期望的那样适用。
你能逐渐解开吗?是的,但不是transform
。为了尽可能便宜(不要在后续流程中触发重新绘制),您需要:
position:relative
)与图像一样高,以保持文档流中的空间自由position:absolute
。因此,即使您为width
设置动画,也不会触发layout
,因为该元素位于文档流之外。.transform-placeholder {
height: 100px;
position: relative;
}
.transform-placeholder .object-fit {
width: 100px;
height: 100px;
animation: object-fit 2.1s infinite;
animation-timing-function: cubic-bezier(.4,0,.2,1);
}
@keyframes object-fit {
0% {
width: 100px;
}
50% {
width: 400px;
}
100% {
width: 100px;
}
}
<div class="transform-placeholder">
<div class="object-fit" style="background-image: url('https://picsum.photos/1600/400?image=857')">
</div>
</div>
<h2>Animation above does not trigger repaint and does not affect layout.</h2>