如何制作 svg 大小以适合其内容?

Zua*_*abi 8 svg

我正在使用 svgs 显示扑克牌。我不希望 svgs 缩放,我不知道会有多少张卡片。不过这些卡有固定的大小。卡片作为 svgs

有没有办法可以轻松地使 svg 容器调整大小以适应内容?谢谢指点。

Pau*_*eau 11

没有自动的方法来做到这一点。但最简单的方法是使用 SVG 内容的边界框,使用getBBox(),然后更新widthheight

document.getElementById("btn").addEventListener("click", resizeSVG);


function resizeSVG() {
  var  svg = document.getElementById("card-table");
  // Get the bounds of the SVG content
  var  bbox = svg.getBBox();
  // Update the width and height using the size of the contents
  svg.setAttribute("width", bbox.x + bbox.width + bbox.x);
  svg.setAttribute("height", bbox.y + bbox.height + bbox.y);
}
Run Code Online (Sandbox Code Playgroud)
svg {
  background: green;
}

.card {
  fill: white;
  stroke: black;
  stroke-width: 2;
}
Run Code Online (Sandbox Code Playgroud)
<svg id="card-table" width="300" height="150">
  <rect x="10" y="10" width="35" height="50" class="card"/>
  <rect x="55" y="10" width="35" height="50" class="card"/>
  <rect x="100" y="10" width="35" height="50" class="card"/>
</svg>


<br>
<button id="btn">Resize SVG</button>
Run Code Online (Sandbox Code Playgroud)


Ish*_*nka 0

您可以将该viewBox属性设置为完整尺寸并设置图表的坐标。完成后,viewBox 会缩放以适应容器的width大小。height

您可以viewBox使用 JavaScript 动态更改尺寸。因此,在渲染图形后,当您知道尺寸时,您可以为 SVG 元素设置相应的边界。

<svg id="svgContainer" height="500" width="500" viewBox="0 0 200 200">
    <polygon points="100,10 40,198 190,78 10,78 160,198" style="fill:lime;stroke:purple;stroke-width:5;fill-rule:nonzero;" />
</svg>
<hr/>
<button onclick="setImageSize(300)">Large</button>
<button onclick="setImageSize(100)">Small</button>
<br/>
<button onclick="setViewBox('0 0 100 100')">viewBox - half</button>
<button onclick="setViewBox('0 0 200 200')">viewBox - full</button>
Run Code Online (Sandbox Code Playgroud)

并使用 JavaScript,

<script>
    function setImageSize(width){
        console.log(width);
        document.getElementById("svgContainer").setAttribute("width", width);
    }

    function setViewBox(viewBoxProperties){
        document.getElementById("svgContainer").setAttribute("viewBox", viewBoxProperties);
    }
</script>
Run Code Online (Sandbox Code Playgroud)