将SVG元素的大小调整为其内容 [英] Adjust size of an SVG-element to its content
问题描述
我想将SVG-Element的尺寸调整为其内容。
I would like to adjust the dimensions of a SVG-Element to its content.
JSfiddle: http://jsfiddle.net/4pD9N/
这里我举了一个例子。 SVG应该收缩以适应每侧的元素+ 10px边距。
换句话说:我想裁剪未使用空间的svg ......
Here I got an example. The SVG should 'shrink' to fit to the elements + 10px margin on each side. In other words: I want to crop the svg for the unused space...
我知道我必须使用 getBBox
。但是如何计算总宽度和高度?
I know that I have to use getBBox
. But how can I calculate the total width and height?
推荐答案
默认情况下,SVG绘图的原点与容器的起源。这意味着您的绘图的(0,0)
位于SVG元素的左上角。要使内容居中,您应该将绘图相对于容器进行转换。
可以通过修改 viewBox
属性来实现(预期的四个值:minx miny width height
)相对于 getBBox()
方法的结果的SVG元素。 http://jsfiddle.net/3cp3c/ 上的实例。
By default, the origin of the SVG drawing is the same as the origin of the container. It means that the (0,0)
of your drawing is in the upper left corner of the SVG element. To center the content, you should translate the drawing relatively to the container.
It can be achieved by modifying the viewBox
attribute (four values expected : "minx miny width height"
) of the SVG element with respect to the result of the getBBox()
method. A live example at http://jsfiddle.net/3cp3c/.
svg.setAttribute("viewBox", (bbox.x-10)+" "+(bbox.y-10)+" "+(bbox.width+20)+" "+(bbox.height+20));
svg.setAttribute("width", (bbox.width+20) + "px");
svg.setAttribute("height",(bbox.height+20) + "px");
这篇关于将SVG元素的大小调整为其内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!