Embedding external SVG in HTML for JavaScript manipulation

后端 未结 2 691
礼貌的吻别
礼貌的吻别 2020-12-04 06:28

I have a SVG image, showing geographical regions. http://upload.wikimedia.org/wikipedia/commons/7/71/Nederland_gemeenten_2009.svg

I want to display the SVG image on

2条回答
  •  孤街浪徒
    2020-12-04 07:16

    My understanding of the question is that there are different aspects to be solved:

    1. How to prepare the image for interaction
    2. How to embed the image in the page
    3. How to use CSS with SVG
    4. How to use JavaScript for interaction

    Preparing the image

    First of all, I'd recommend to clean up the image. Inkscape leaves all kind of stuff there that you don't need, which includes elements and attributes in the sodipodi: and inkscape: namespaces as well as repetitive and/or redundant style attributes. You don't have to remove that, but it saves you some bandwidth/loading time, and if you want to work with CSS stylesheets, than the style attributes are in your way.

    In your example file, you have 472 times the same style attribute. Remove all of them and create an equivalent CSS rule once.

    You might also add some info about the municipalities to the markup. You could e.g. change the IDs of each path representing a municipality according to its name. You could also use a data-* attribute for this purpose. The latter has the advantage that you can use spaces. See below for how this is useful for interaction, especially with CSS.

    Embedding the image

    I'd recommend using the SVG inline, especially if you want to interact with CSS/JavaScript. This means, you just add the SVG markup to your HTML, or you load and insert it using Ajax. The latter has the benefit that the surrounding page loads faster and feels more responsive.

    An example of an inline SVG element:

    A simplified example of how to load SVG using Ajax:

    xhr = new XMLHttpRequest();
    xhr.open("GET","my.svg",false);
    // Following line is just to be on the safe side;
    // not needed if your server delivers SVG with correct MIME type
    xhr.overrideMimeType("image/svg+xml");
    xhr.onload = function(e) {
      // You might also want to check for xhr.readyState/xhr.status here
      document.getElementById("svgContainer")
        .appendChild(xhr.responseXML.documentElement);
    }
    xhr.send("");
    

    How to use CSS

    SVG can be styled just like HTML. Of course, SVG has it's own set of properties, like fill-opacity or stroke-dasharray and does not support a lot of HTML's properties, like margin, position or the like. But the selector mechanisms are 100% the same.

    You can mix the CSS for your inline SVG with the CSS for your HTML, either inside a