Take the 2-minute tour ×

I get an XML or JSON with paths only, and I need to recreate the SVG image.

I create an empty

<svg xmlns='http://www.w3.org/2000/svg' version='1.1'></svg>,

I add a <g transform="scale(1 -1)" fill='#aaa' stroke='black' stroke-width='5' ></g> in it, and then in this element I add all of the paths in it (e.g. <path d= ... />).

In the end I get a SVG image, but because I haven't set the viewBox attribute in the SVG element the image isn't properly displayed - when I open it in browser, a part of it is displayed full size.

Can the viewBox be calculated from the values from the paths?

Thank you!

share|improve this question
What do you mean by "a part of it is displayed full size" ? –  mihai Apr 5 '12 at 13:40
For example if I have a 400x400px SVG, a par of it - e.g. a 50x50 from the down left corner - I get it full size. –  Martin Spa Apr 6 '12 at 8:57
add comment

2 Answers

Similar to Martin Spa's answer, but a better way to do get the max viewport area is using the getBBox function:

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.

share|improve this answer
add comment
up vote 2 down vote accepted

OK so I solved it the following way:

  1. removed all letters from the paths string and made an array out of it with

    var values = pathValue.split('L').join(' ').split('M').join(' ').split('z').join('').split(' ');

  2. found max and min from those values:

    var max = Math.max.apply( Math, values );

    var min = Math.min.apply( Math, values );

  3. set the viewBox:

    viewBox = max min max max

This worked in my case excellent. Hope that it will be helpful to someone else too.

share|improve this answer
That sounds good. I understand the problem now. Initially I thought you could just set the viewBox to a fixed value, but I guess that wouldn't work because if the image is too big, part of if won't get displayed. –  mihai Apr 6 '12 at 13:47
nice : > btw an easier way to do the values bit: path.match(/(\-?\d+(\.\d+)?)/gi). this also works with other characters like q and t which can be in paths –  alzclarke Apr 21 '12 at 13:12
add comment

Your Answer


