admin管理员组文章数量:1202830
I would like to adjust the dimensions of a SVG-Element to its content.
JSfiddle: /
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...
I know that I have to use getBBox
. But how can I calculate the total width and height?
I would like to adjust the dimensions of a SVG-Element to its content.
JSfiddle: http://jsfiddle.net/4pD9N/
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...
I know that I have to use getBBox
. But how can I calculate the total width and height?
2 Answers
Reset to default 15By 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");
var svg = document.getElementsByTagName("svg")[0];
var bb=svg.getBBox();
var bbx=bb.x;
var bby=bb.y;
var bbw=bb.width;
var bbh=bb.height;
var vb=[bbx,bby,bbw,bbh];
svg.setAttribute("viewBox", vb.join(" ") );
本文标签: javascriptAdjust size of an SVGelement to its contentStack Overflow
版权声明:本文标题:javascript - Adjust size of an SVG-element to its content - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738657514a2105226.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论