Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating viewBox parameters based on path elements in SVG

Tags:

svg

viewbox

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!

like image 606
Martin Spa Avatar asked Apr 05 '12 12:04

Martin Spa


People also ask

How do I scale SVG viewBox?

Just set the viewBox on your <svg> , and set one of height or width to auto . The browser will adjust it so that the overall aspect ratio matches the viewBox .

What is viewBox in SVG image?

The viewBox attribute defines the position and dimension, in user space, of an SVG viewport. The value of the viewBox attribute is a list of four numbers: min-x , min-y , width and height .

Is viewBox required for SVG?

viewbox is like a second set of virtual coordinates – all vectors inside the SVG will use the viewbox, while you can manipulate the actual height, width properties of the SVG without affecting the inside,. An SVG with a viewBox is so much easier to work with. I would never put an SVG together without one.

What is path D in SVG?

The d attribute defines a path to be drawn. A path definition is a list of path commands where each command is composed of a command letter and numbers that represent the command parameters.


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.

like image 193
alzclarke Avatar answered Jan 04 '23 21:01

alzclarke


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.

like image 32
Martin Spa Avatar answered Jan 04 '23 20:01

Martin Spa