如何使SVG容器拥抱其内容? [英] How to make a SVG container hug its contents?

查看:99
本文介绍了如何使SVG容器拥抱其内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个项目中,其中会根据用户提供的输入自动生成一些SVG标签.例如,我最常见的情况是在<svg>容器中可能有很多SVG对象(即rect,椭圆,多边形等).

I am working on a project where some SVG tags are auto-generated based on the user provided input. For instance the most common scenario I have is that I may have many SVG objects (i.e. rect, ellipse, polygon, etc.) inside a <svg> container.

现在的问题是,无论其内容如何,​​我的容器SVG都具有一定的长度和宽度.我正在尝试使我的容器SVG标签仅具有如此长的长度和宽度,以使其可以包含其内容,但不能有空格.

Now the issue is that my container SVG has a certain length and width regardless of its contents. I am trying to make my container SVG tag to only have so much length and width so that it can contain its content but no blank space.

例如:在这个小提琴中带有id=svg1的SVG远大于其内容需要它.

For example: in this fiddle the SVG with id=svg1 is much larger than its contents need it to be.

如何制作适当大小的SVG容器?

How can i make the SVG container of appropriate size?

注意:我不知道要将哪些形状放置在SVG容器中以及将它们放置在何处.此外,SVG可以在其中包含另一个<svg>标签,并且形状可以位于内部SVG中.

Note: I don't know which shapes are going to be put inside the SVG container and where they are going to be placed. Also, the SVG can contain another <svg> tag inside it and shapes can be inside this inner SVG.

注2:在某些情况下,可能需要增加SVG容器的宽度和高度,以便不截断内容物.阿洛斯,出于种种原因,我必须只使用纯HTML/CSS解决方案.

Note 2: In some cases the width and height of the SVG container may be needed to be increased so as to not truncate the contents. Alos, it is imperative that i only use a pure HTML/CSS solution for certaion reasons.

推荐答案

好吧,如果我理解得很好,那么您希望其子级"所在的"svg标签"具有精确的高度"和宽度".

Ok, if i understood it well, then you want your 'svg tag' of exact 'height' and 'width' in which its 'child' resides.

一种可能的解决方案是:-

one possible solution would be:-

(假设您的svg位于0,0)

(assuming your svg is positioned at 0,0)

  1. 您需要跟踪在svg中绘制了哪个元素(我希望您已经在这样做).
  2. 然后,您需要使用"getBbox()"来获取其高度"和宽度"
  3. 现在,您需要计算子"元素相对于位置(0,0)的确切位置.

让我们举个例子

var svgwidth=500;
var svgheight=500;

<svg id="svg1" width="500" height="500">
</svg>

现在假设用户在其中绘制一个矩形.

now let say user draw a rectangle in it.

<rect id="rect1" x="0" y="0" height="200" width="300"></rect>

现在我们需要为"svg"确定确切的宽度"和高度".

now we need to determine exact 'width' and 'height' for our 'svg'.

var rect1=document.getElementById('rect1');
var bbox=rect1.getBBox();

var widtharea=bbox.x+bbox.width;
var heightarea=bbox.y+bbox.height;

现在将"widtharea"与"svgwidth"进行比较,如果其大于"svgwidth",则更新"svgwidth"的值.类似地将"heightarea"与"svgheight"进行比较

Now compare 'widtharea' with 'svgwidth', if its larger then 'svgwidth', update value of 'svgwidth'. similarly compare 'heightarea' with 'svgheight'

每次用户在svg中创建任何元素时,您都需要执行上述步骤.

you need to perform above step every time user create any element in svg.

这篇关于如何使SVG容器拥抱其内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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