我有一个动态大小的 SVG 元素。我想根据需要将它及其内容缩放到特定的像素大小(而不是像素)。
这是无效的:
transform: scale(100px);
我对 SVG 的了解中等,所以也许有更好的方法,但是在绘制内容后设置 SVG 元素的高度/宽度只会导致其内容溢出,因为它们是“绝对”而不是“相对”路径。
使用 JS,您可以获得相对大小:
const scaleX = targetWidth / svg.offsetWidth;
const scaleY = targetHeight / svg.offsetHeight;
svg.style.scale = `${scaleX}px ${scaleY}px`; //untested but you get the idea
我希望在 CSS3 的某个地方有一种我不知道的“scaleTo”,或者是完成这个的巧妙技巧。权威的“否”是可以接受的答案。
如果您有权访问 svg 的 html,则可以删除 svg 元素的宽度和高度属性,并将其替换viewBox
为 x/y 位置设置为 0 且宽度/高度对设置为您的值的属性删除:
<svg width="300" height="200">
<!-- change to: -->
<svg viewBox="0 0 300 200">
然后,您可以将 svg 元素放在一个大小合适的 div 中,并将 svg 的 css 宽度和高度设置为 100%:
.svgContainer svg {
width: 100%;
height: 100%;
}
请参阅工作片段以比较效果,我已将相同的 svg 压缩到一个较小的 div 中,有和没有viewBox
集合。
请注意,对于动态调整大小,div 容器必须动态调整大小,viewBox
设置为 100% 容器宽度和高度的 svg 版本将自行处理。如果容器 Div 的大小是 % 而不是像素,它会随着浏览器的视口而增长和缩小。
如果您无法访问 html 标记,您可以通过使用 javascript 检索 svg 的width
和height
属性并为viewBox
.
更多关于viewBox
:https ://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/viewBox
.svgContainer {
width: 100px;
}
.svgContainer svg {
margin: 0;
width: 100%;
height: 100%;
}
<p> 300x200 svg rendered outside of a container:</p>
<svg width="300px" height="200px">
<rect x="0" y="0" width="100%" height="100%" fill="red" stroke="blue"/>
<rect x="100" y="50" width="100" height="50" fill="yellow"/>
<rect x="30" y="20" width="20" height="35" fill="blue"/>
</svg>
<p> same 300x200 svg rendered inside sized div:</p>
<div class="svgContainer">
<svg width="300px" height="200px">
<rect x="0" y="0" width="100%" height="100%" fill="red" stroke="blue"/>
<rect x="100" y="50" width="100" height="50" fill="yellow"/>
<rect x="30" y="20" width="20" height="35" fill="blue"/>
</svg>
</div>
<p>svg modified to use viewbox attribute values, inside sized div</p>
<div class="svgContainer">
<svg viewBox="0 0 300 200">
<rect x="0" y="0" width="100%" height="100%" fill="red" stroke="blue"/>
<rect x="100" y="50" width="100" height="50" fill="yellow"/>
<rect x="30" y="20" width="20" height="35" fill="blue"/>
</svg>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句