Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining an original SVG viewBox via javascript

Tags:

Our system loads SVG files programmatically into HTML via AJAX. A typical SVG file begins with:

 <svg xmlns='http://www.w3.org/2000/svg' viewBox='0,0 65415,41616' xml:space='preserve' height='50.000cm'  width='50.000cm' xmlns:xlink='http://www.w3.org/1999/xlink 

But strangely in JavaScript there seems to be no way of getting this 'viewBox' back from the SVG DOM - either as a string, or as a set of values. Under Mozilla, for example, firebug reports that the svg node has 5 of the 6 attributes we specifiy - namely: xmlns, xml:space, height, width and xmlns:xlink. But ViewBox is conspicuously missing from this list.

Is there anyway to programmatically retrieve this value? - where is it in the SVG DOM? (We cannot introduce 3rd party libraries).

like image 855
Tony Eastwood Avatar asked Oct 06 '11 14:10

Tony Eastwood


People also ask

Can I remove viewBox from SVG?

To remove the viewBox and get the equivalent transform, you can just surround the contents of the SVG with a group element ( <g> ). Then give that the equivalent transform. So for an equivalent transform, we have to combine a scale and a translate.

What is SVG viewBox attribute?

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 view port in SVG?

The viewport is the visible area of the SVG image. An SVG image can logically be as wide and high as you want, but only a certain part of the image can be visible at a time. The area that is visible is called the viewport. You specify the size of the viewport using the width and height attributes of the <svg> element.


1 Answers

  1. Go to http://phrogz.net/SVG/svg_in_xhtml5.xhtml
  2. Open your web browser console
  3. Type the code:

    var svg = document.querySelector('svg'); var box = svg.getAttribute('viewBox'); box.split(/\s+|,/); 
  4. Observe the glorious response:

    ["-350", "-250", "700", "500"] 
  5. Alternatively, type the code:

    var box = svg.viewBox.baseVal; [ box.x, box.y, box.width, box.height ] 
  6. Observe the glorious response:

    [ -350, -250, 700, 500 ] 

In other words: yes, you can get the viewBox from the DOM, both as a standard DOM 2 attribute as well as an explicit ECMASCript binding.

like image 111
Phrogz Avatar answered Sep 17 '22 04:09

Phrogz