Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active February 22, 2020 09:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save mbostock/1014829 to your computer and use it in GitHub Desktop.
Save mbostock/1014829 to your computer and use it in GitHub Desktop.
External SVG
license: gpl-3.0
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="https://d3js.org/d3.v4.js"></script>
<script>
d3.xml("rect01.svg").mimeType("image/svg+xml").get(function(error, xml) {
if (error) throw error;
document.body.appendChild(xml.documentElement);
});
</script>
Display the source blob
Display the rendered blob
Raw
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="12cm" height="4cm" viewBox="0 0 1200 400"
xmlns="http://www.w3.org/2000/svg" version="1.1">
<desc>Example rect01 - rectangle with sharp corners</desc>
<!-- Show outline of canvas using 'rect' element -->
<rect x="1" y="1" width="1198" height="398"
fill="none" stroke="blue" stroke-width="2"/>
<rect x="400" y="100" width="400" height="200"
fill="yellow" stroke="navy" stroke-width="10" />
</svg>
@fcsds
Copy link

fcsds commented Feb 4, 2016

Question: How do I add other svg objects on top of the rectangle?

@roadluac2016
Copy link

How i can put SVG external file with d3.select("#mysvg").append()... ?

@wjentner
Copy link

Hi,

I know the question is kinda far in the past but perhaps it'll help someone:

The way I did it was (note that this is d3v5):

        d3.svg('external.svg').then((svg) => {
            //the external svg looks like this: [...]<svg><g>[...]</g></svg> so I select the g element and inject it into my svg
            const gElement = d3.select(svg).select('g'); 
            d3.select('#mysvg').node().appendChild(gElement.node());
        });

With d3.select().append() it did not work in my case.
I don't know if my approach is best practice but it certainly works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment