Search code examples
svgzoominglimitsviewbox

setting viewbox coordinates to extents of svg drawing


I have a set of dynamically created svg objects. Some of them have rather complicated transformations applied to. I mean this is meaningless that I want to calculate maximum and minimums of X & Y of these objects. I want viewbox (or any similar tag that may be useful) to show all these objects without engaging me in calculating extents of drawing objects.

Could you please help?

Thanks


Solution

  • You can use getBBox() on the path element to get the extents of your drawing.

    var clientrect = path.getBBox();
    var viewBox = clientrect.x+' '+clientrect.y+' '+clientrect.width+' '+clientrect.height;
    

    You can then set the viewbox to these co-ordinates.

    n.b. i think you can change the viewbox of an svg after it's rendered so you may have to re-render the svg.