自动调整SVG大小? [英] Autosize an SVG?

查看:138
本文介绍了自动调整SVG大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码演示

我有一个高度未知的SVG.我可以在加载json并使用javascript + math之后弄清楚它,但是我可以使用任何CSS来动态调整它的大小吗?

I have a SVG with an unknown height. I can figure it out after I load in json and use javascript+math but is there any css I can use to dynamically size it?

css:

svg {
  width: 500px;
  height: 9000px;
}
.tabme {
  border:3px solid red;
  height: 200px;
   overflow:scroll;
}

html:

<div class="tabme">
  <div id="Chart">
    <div class="chartbody" />
    <svg>
      <rect width="190" y="0" height="16" x="175" />
      <rect width="190" y="20" height="16" x="175" />
      <rect width="190" y="40" height="16" x="175" />
      <rect width="190" y="60" height="16" x="175" />
      <rect width="190" y="80" height="16" x="175" />
      <rect width="190" y="100" height="16" x="175" />
      <rect width="190" y="120" height="16" x="175" />
      <rect width="190" y="140" height="16" x="175" />
      <rect width="190" y="160" height="16" x="175" />
      <rect width="190" y="180" height="16" x="175" />
      <rect width="190" y="200" height="16" x="175" />
      <rect width="190" y="220" height="16" x="175" />
      <rect width="190" y="240" height="16" x="175" />
      <rect width="190" y="260" height="16" x="175" />
      <rect width="190" y="280" height="16" x="175" />
      <rect width="190" y="300" height="16" x="175" />
    </svg>
  </div>
</div>

推荐答案

如果SVG元素没有任何width和height属性,则width/height应该为

If the SVG element does not have any width and height attributes, then the width/height should be calculated according to the CSS specs, as pointed out by Robert Longson. However, those values will not reflect the proper dimensions of the SVG's content. You can find out the proper dimensions and placement using getBBox():

// Javascript to run after document load
var svg = document.getElementsByTagName("svg")[0];
var bbox = svg.getBBox();
svg.setAttribute("width", bbox.width + "px");
svg.setAttribute("height", bbox.height + "px");
svg.setAttribute("viewBox", `${bbox.x} ${bbox.y} ${bbox.width} ${bbox.height}`);

<svg xmlns="http://www.w3.org/2000/svg" style="background-color: red">
  <rect x="30" y="40" width="50" height="60"/>
</svg>

这篇关于自动调整SVG大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆