0

I've just lost my whole morning to what should have been a very basic and straightforward task. Sorry if the solution to this problem is obvious to you, I'm beginning on D3.js and Javascript.

I'm looking to load, in D3, an external svg file, and have it as an inline svg to do further operations, not as a static image, and working on local files. I don't understand how there couldn't be a way to do such a simple and basic thing. I've tried anything I could:

<!DOCTYPE html>
<html>
<head>
<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
<script>
d3.xml('nameOfMysvgFile.svg')
    .then(data => {
        document.body.append(data.documentElement)
    })
</script>
</body>
</html>

So far the best I achieved was to load my svg as an object (as done here: http://dahlström.net/svg/html/get-embedded-svg-document-script.html), and then I'm stuck, as I can't do any operation in Javascript on that object. How to transfer the contents of the object to inline svg? Or how to take out that #document "wrapping" that prevents from doing anything on the svg? Or even better, add the contents to an existing svg container (mySvgContainer.append("g").[magic command to add the contents of external svg file])?

Dric
  • 87
  • 13
  • Are you running a server for this or are you accessing the file system directly? – altocumulus Mar 15 '22 at 16:28
  • I'm accessing the files directly – Dric Mar 15 '22 at 16:59
  • 2
    That is your problem: you cannot access files from the file system. You'll need to set up at least a basic server for this to work. Same as here: [*"Importing local json file using d3.json does not work"*](/q/17214293). – altocumulus Mar 15 '22 at 17:14
  • You could look at a combination of this: https://stackoverflow.com/questions/40032384/can-i-append-a-literal-svg-element-with-d3 and this: https://developer.mozilla.org/en-US/docs/Web/API/FileReader – Robin Mackenzie Mar 16 '22 at 11:15
  • I've switched to my company's server (but have to work on PHP scripts, which I'm also new to, so again another layer of complexity), but I can't get any solution to work again, so I'm still investigating. @Robin Mackenzie I am sorry but I don't understand your suggestion and how the 2 links are related. Sorry if this should be trivial, I am still beginning on Javascript and still wrapping my head around some concepts. Could you please elaborate? – Dric Mar 16 '22 at 15:00
  • 1
    I set up a local server and now this example (http://www.zevross.com/blog/2019/08/20/load-external-svgs-with-d3-v5/) works finally. – Dric Mar 16 '22 at 15:37

0 Answers0