Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 to load the SVG file successfully, using .load(), having inserted the SVG tree inside the DOM. But I would like to try svg.js to manipulate the elements, but in the documentation I cannot find a way to initialize the library using an existing SVG element, where I will get the objects.

Idea is to access the loaded SVG element (or load it directly with the svg.js library), copy the single objects to another element and move them where I need. How to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
140 views
Welcome To Ask or Share your Answers For Others

1 Answer

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'));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...