2

I'm trying to figure out if it's possible to insert an existing external SVG image (saved as a .svg) into an SVG object rendered with Javascript (using, in my case, d3.js).

I can't seem to find anything related to this, yet it seems like something that should be fairly obvious to do. I figure I can always attach it as a pattern, but that seemed like it was incorrect, considering.

Thanks in advance!

NotSimon
  • 1,795
  • 1
  • 21
  • 31
  • 3
    You have two options. If you just want to use the external SVG as a static image (like a logo), use d3 to create an `` element and reference the SVG file in the `xlink:href` attribute. If you want the external SVG to become part of your DOM structure, able to interact with the rest of your content, [see this question](http://stackoverflow.com/a/21289967/3128209). – AmeliaBR May 27 '14 at 21:31

1 Answers1

2

You can use d3.xml to import the SVG document as an XML document and insert the content of the XML in a DOM element.

// Create the SVG Element with D3
var div = d3.select('#example'),
    svg = div.append('svg')
     .attr('width', 200)
     .attr('height', 200);

var g = svg.append('g')
   .attr('class', 'svg-container');

var url = 'http://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg';

// Load the XML data
d3.xml(url, 'image/svg+xml', function(error, xml) {

    // Insert the SVG image as a DOM node
    g.node().appendChild(document.importNode(xml.documentElement, true));

    // Acess and manipulate the iamge
    var svgImage = g.select('svg');

    svgImage
        .attr('width', 50)
        .attr('height', 50);
});

A working jsBin is available. Regards,

Pablo Navarro
  • 8,244
  • 2
  • 43
  • 52