我有一個動態大小的 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”,或者是完成這個的巧妙技巧。權威的“否”是可以接受的答案。
uj5u.com熱心網友回復:
如果您有權訪問 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/453128.html
上一篇:如何簡化這些CSS選擇器?
下一篇:引導寬度溢位,不適合形成內容
