Obtaining an original SVG viewBox via javascript

后端 未结 4 1770
南笙
南笙 2021-01-07 17:53

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

 

        
4条回答
  •  一向
    一向 (楼主)
    2021-01-07 18:35

    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.

提交回复
热议问题