Calculating viewBox parameters based on path items in SVG
I am only getting XML or JSON with paths and I need to recreate the SVG image.
I create empty
<svg xmlns='http://www.w3.org/2000/svg' version='1.1'></svg>
,
I add to it <g transform="scale(1 -1)" fill='#aaa' stroke='black' stroke-width='5' ></g>
and then in this element I add all paths to it (like <path d=
... />
).
I end up with an SVG image, but since I didn't set the viewBox attribute on the SVG element, the image doesn't display as expected - when I open it in a browser, part of it is displayed at full size.
Is it possible to compute a viewBox from values from paths?
Thank!
source to share
OK, so I solved it like this:
-
removed all letters from the path string and made an array from it with
var values = pathValue.split('L').join(' ').split('M').join(' ').split('z').join('').split(' ');
-
found max and min of these values:
var max = Math.max.apply( Math, values );
var min = Math.min.apply( Math, values );
-
install the viewBox:
viewBox = max min max max
This worked fine in my case. Hope it will be helpful for someone else too.
source to share
Similar to Martin Spa's answer, but the best way to get the maximum viewport area is using the getBBox function:
var clientrect = path.getBBox();
var viewBox = clientrect.x+' '+clientrect.y+' '+clientrect.width+' '+clientrect.height;
Then you can set the window to view these coordinates.
nb I think you can change the svg viewport after displaying it, so you may need to re-display the svg.
source to share