我试图获得与在 CSS 中使用
background-size: cover
相同的效果,但通过使用 SVG 过滤器 - 特别是 feImage
。
div {
width: 10em;
aspect-ratio: 1;
background: gold
}
.svg { filter: url(#f) }
.css {
background: url(https://images.unsplash.com/photo-1705339613128-28b8d900fb52?w=600) 50%/ cover
}
svg[height='0'] { position: fixed }
<svg width='0' height='0'>
<filter id='f' x='0' y='0' width='100%' height='100%' primitiveUnits='objectBoundingBox'>
<feImage xlink:href='https://images.unsplash.com/photo-1705339613128-28b8d900fb52?w=400'
preserveAspectRatio='xMidyMid meet'/>
</filter>
</svg>
<em>Result using SVG filter</em>
<div class='svg'></div>
<em>Desired result should look like</em>
<div class='css'></div>
preserveAspectRatio='xMidyMid meet'
应该是默认值,所以我什至不需要添加它,但甚至添加它似乎也不起作用。
我什至不需要设置
width
和 height
,因为它们应该默认为过滤器区域 - 也根据 MDN。
我在这里缺少什么?我怎样才能使
feImage
覆盖整个 div/过滤器区域而不失真(preserveAspectRatio='none'
实现覆盖部分,但引入失真)。
您想要 xMidYMid 并切片。 SVG 区分大小写,您想要切掉图像的两侧并使用高度而不是宽度来填充它。
div {
width: 10em;
aspect-ratio: 1;
background: gold
}
.svg { filter: url(#f) }
.css {
background: url(https://images.unsplash.com/photo-1705339613128-28b8d900fb52?w=600) 50%/ cover
}
svg[height='0'] { position: fixed }
<svg width='0' height='0'>
<filter id='f' x='0' y='0' width='100%' height='100%' primitiveUnits='objectBoundingBox'>
<feImage xlink:href='https://images.unsplash.com/photo-1705339613128-28b8d900fb52?w=400'
preserveAspectRatio='xMidYMid slice'/>
</filter>
</svg>
<em>Result using SVG filter</em>
<div class='svg'></div>
<em>Desired result should look like</em>
<div class='css'></div>