Is it possible to import svg shapes in d3.js?

2020-02-08 04:26发布

First day with d3.js, going well, but I need to change my placeholder circle shapes to something a litte more complex.

Can SVG shapes that I've created in, say, Illustrator, be "imported" into a d3.js chart?

I know I can redraw it in d3... but my head hurts right now... er...

it's a simple bubble with a point:

<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 13.0.2, SVG Export Plug-In . SVG Version: 6.00 Build 14948)  -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="77px" height="41px" viewBox="0 0 77 41" enable-background="new 0 0 77 41" xml:space="preserve">
<path fill-rule="evenodd" clip-rule="evenodd" fill="#999999" d="M0,13C0,5.82,5.82,0,13,0h51c7.18,0,13,5.82,13,13s-5.82,13-13,13
    H47l-7,15l-7-15H13C5.82,26,0,20.18,0,13z"/>
</svg>

Can that be imported as a shape?

Or is there a way to translate that path directly in d3js?

Thanks!

标签: svg d3.js
1条回答
▲ chillily
2楼-- · 2020-02-08 04:48

If by "imported" you mean be part of the page markup and then used by your d3 code, then yes you can use svg defs element to hold the definition of your custom shape. Then later in your code you create a use element to reference it:

var node = svg.selectAll("g.node")
  .data(nodes)
  .enter()
  .append("g")
  .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; } )

node.append("use")
  .attr("xlink:href","#myshape")

Here is a full example of the above approach. I used Inkscape but the concept is the same:

http://bl.ocks.org/explunit/5988971

Note that the xlink namespace in the svg definition is important for the use element to work properly, and I see you have it your code already:

xmlns:xlink="http://www.w3.org/1999/xlink"

If by "imported" you mean loaded on-the-fly, then a different approach is needed, as suggested by @LarsKotthoff. But it sounds like you just want to reuse an existing shape definition, and the above approach lets you do it. The <g> element sets the position of the shapes, and then child node <use> is added to pull in the actual shape defined earlier.

The definition of the shape is in the svg element in the body, not in the javascript itself. This differs from many D3.js examples which have the svg element created dynamically by the javascript code.

The only connection between the two is the string ID that you put in the href ("myshape" in this case) to match the id in the defs section:

node.append("use").attr("xlink:href","#myshape")
查看更多
登录 后发表回答