简体   繁体   中英

The best way to import complex SVG graphics into D3 charts

Assume, I have some relatively complex SVG graphics as a set of files, for example, looking like these icons:

图标

I want to use them in my D3-powered charts. So, I can go with <defs> and <use> tags and inject them as symbols. But I want to make them less solid monolithic assets, but more like fully active and editable graphic elements. I know I can manually import all paths from icons SVG code like this:

svg.append('path').attr('d', 'M7.5,5.809c-0.869,0-1.576-0.742-1.576-1.654c0-0.912,0.707-1.653,1.576-1.653 c0.87,0,1.577,0.742,1.577,1.653C9.077,5.067,8.369,5.809,7.5,5.809z')

But this doesn't seem to be a quick to run scenario as I need to build some script to convert icons to code like that or do it manually, but I want to have some simple workflow similar to just editing an icon Illustrator, saving, importing.

As a result, I want to have full control on the all the shapes and paths inside each icon. How you think it can be done in the most straightforward and D3 way?

You can import your SVGs using d3.xml and then insert the xml directly into your document. In the example code below I create a g in a svg element and then insert an image into that:

<script>
  var height = 500;
  var width = 700;

  var vis = d3.select("#vis").append("svg")
    .attr("width", width).attr("height", height)
  var g = vis.append("g").attr("id", "image");

  d3.xml("drawing.svg", "image/svg+xml", function(xml) {
    g.each(function() {
      this.appendChild(xml.documentElement);
    });
  });
</script>

I guess you could also select separate icons from one SVG document containing multiple icons and insert each separately. I expect styling will be lost when the SVG document stores it's styling in a stylesheet and not directly in the elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM