Obtaining an original SVG viewBox via javascript

2020-03-08 08:34发布

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).

4条回答
ゆ 、 Hurt°
2楼-- · 2020-03-08 08:46

Even easier, put an id in your svg then :

document.getElementById("your_id").getAttribute("viewBox");
查看更多
爷的心禁止访问
3楼-- · 2020-03-08 08:51

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 that might be the property you're looking for.

查看更多
甜甜的少女心
4楼-- · 2020-03-08 08:53

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");
查看更多
做自己的国王
5楼-- · 2020-03-08 09:10
  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.

查看更多
登录 后发表回答