Obtaining an original SVG viewBox via javascript
- Go to http://phrogz.net/SVG/svg_in_xhtml5.xhtml
- Open your web browser console
Type the code:
var svg = document.querySelector('svg'); var box = svg.getAttribute('viewBox'); box.split(/\s+|,/);
Observe the glorious response:
["-350", "-250", "700", "500"]
Alternatively, type the code:
var box = svg.viewBox.baseVal; [ box.x, box.y, box.width, box.height ]
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.
Above receipes gave me all zeros for the x, y, width and height viewBox attributes -- unless at least one of them was changed programmatically.
I finally succeded with
var width = document.getElementById("mysvg").getAttribute("width");
Even easier, put an id in your svg then :
document.getElementById("your_id").getAttribute("viewBox");
You'll want to take a look at the SVGFitToViewBox
interface, which specifies the viewBox
property. The interface for svg
elements, SVGSVGElement
, extends that interface, so this property is available on the element objects:
const svgElement = document.getElementById("example-svg");
const {x, y, width, height} = svgElement.viewBox.baseVal;