Display an SVG image at the middle of an SVG path

2019-07-23 02:51发布

I have a force directed graph with different size nodes. I want to display a custom icon in the middle of each path connecting two nodes. From the d3 examples I found the way to display images within the nodes. However, when I try the same technique on the paths, the images are not shown.

var path = svg.append("svg:g").selectAll("path").data(force.links());

var pathEnter = path.enter().append("svg:path");

pathEnter.attr("class", function(d) {
    return "link " + d.target.type;
})

pathEnter.append("svg:g").append("image")
    .attr("xlink:href","http://127.0.0.1:8000/static/styles/images/add.png")
    .attr("x",0).attr("y",0).attr("width",12).attr("height", 12)
    .attr("class", "type-icon");

1条回答
Anthone
2楼-- · 2019-07-23 03:30

I guess I need a bit more patience before asking a question. The way I solved the problem is:

var icon = svg.append("svg:g").selectAll("g")
.data(force.links()).enter().append("svg:g");

icon.append("image").attr("xlink:href","imagePath")
  .attr("x", -20)
  .attr("y", -2)
  .attr("width", 12).attr("height", 12)
        .attr("class", "type-icon");

And then in the tick function:

        icon.attr("transform", function(d) {
            return "translate(" +((d.target.x+d.source.x)/2) + "," +
                ((d.target.y+d.source.y))/2 + ")";
        });

to get the center point between the two nodes.

查看更多
登录 后发表回答