Loading a SVG file with svg.js

前端 未结 3 1129
青春惊慌失措
青春惊慌失措 2020-12-14 12:36

I have a HTML5 page with a SVG element in it. I would like to load a SVG file, extract some elements from it and dispose them one by one with a script.

I used jQuery

相关标签:
3条回答
  • 2020-12-14 12:52

    If you know the id's of elements you can use the SVG.get method after importing raw svg:

    SVG.get('element_id').move(200,200)
    

    The library was moved to GitHub and the metioned documentation is at http://svgjs.com/referencing/


    Old link: http://documentup.com/wout/svg.js#referencing-elements

    0 讨论(0)
  • 2020-12-14 13:01

    You should take a look at the svg.import.js plugin

    The documentation says...

    All imported elements with an id will be stored. The object with all stored elements is returned by the import method:

    var rawSvg = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg [...]>"';
    var draw = SVG('paper');
    var store = draw.svg(rawSvg);
    
    store.polygon1238.fill('#f06');
    
    0 讨论(0)
  • 2020-12-14 13:09

    Given an SVG file 'image.svg' containing

    <svg viewBox="0 0 500 600" version="1.1">
      <rect x="100" y="100" width="400" height="200" fill="yellow" 
       stroke="black" stroke-width="3"/>
    </svg>
    

    and a file 'index.html' containing

    <html>
      <head>
        <script type="text/javascript" src="svg.js"></script>
        <script type="text/javascript" src="jquery-X.X.X.js"></script>
        <script type="text/javascript" src="script.js"></script>
      </head>
      <body>
        <div id="svgimage"></div>
      </body>
    </html>
    

    then if file 'script.js' contains

    $(document).ready(function() {
    
      var image = SVG('svgimage');
      $.get('image.svg', function(contents) {
        var $tmp = $('svg', contents);
        image.svg($tmp.html());
      }, 'xml');
    
      $('#svgimage').hover(
        function() {
          image.select('rect').fill('blue');
        },
        function() {
          image.select('rect').fill('yellow');
        }
      );
    
    });
    

    then the SVG image will display and moving the mouse pointer in and out of the browser window will change the color of the rectangle from yellow to blue.

    You should now be able to substitute any SVG image file and define any number of functions to manipulate the image using the SVG.js library. The important thing to realize is that calls to SVG.js methods will not succeed if they take place before the $(document).ready function has returned.

    For bonus points, I also found copying the values of the 'viewBox', 'width' and 'height' attributes by adding the following lines after the declaration of '$tmp' to work best for successfully displaying the contents of arbitrary SVG files:

        image.attr('viewBox', $tmp.attr('viewBox'));
        image.attr('width', $tmp.attr('width'));
        image.attr('height', $tmp.attr('height'));
    
    0 讨论(0)
提交回复
热议问题