Adjust size of an SVG-element to its content

后端 未结 2 1410
星月不相逢
星月不相逢 2021-01-11 13:43

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 s

相关标签:
2条回答
  • 2021-01-11 14:30
    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(" ") );
    
    0 讨论(0)
  • 2021-01-11 14:37

    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");
    
    0 讨论(0)
提交回复
热议问题