最佳答案
没有自动的方法来做到这一点。但最简单的方法是使用 SVG 内容的边界框,使用 getBBox()
,然后更新 width
和 height
从那。
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);
}
svg {
background: green;
}
.card {
fill: white;
stroke: black;
stroke-width: 2;
}
<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>
关于svg - 如何制作 svg 大小以适合其内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50813950/