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

标签 svg

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

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

最佳答案

没有自动的方法来做到这一点。但最简单的方法是使用 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);
}
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/

相关文章:

svg - 如何确定鼠标事件附近的 SVG 元素?

javascript - svg的动态 Angular 线性渐变

svg - 如何使用d3.js更新现有svg元素的填充颜色?

css - SVG animatetransform 旋转,不能在 ie 和 firefox 上完美运行

javascript - 调整组的比例以确保内部形状在 d3 js 中尽可能大

javascript - 像 SWF 一样缩放 SVG (Raphael.js)

java - Android 中的模糊 svg 图像

css - Safari 在 SVG Logo 的顶部和底部提供填充

javascript - 如何在svg中动态显示文本

html - CSS半月背景图像 mask