D3.js force layout - edge label placement/rotation

十年热恋 提交于 2019-12-05 01:24:54

@LarsKotthoff is correct that the textPath has to follow the direction of the path. In this case, the direction of the path defines not only the arc direction, but the attachment of the arrow marker on the end - this makes it tricky to swap directions on the fly, as you have to move the marker too.

The simpler solution (though maybe not the best if you have a large number of links) is to "shadow" the real link path with an invisible path used just for text:

var link = svg.append("svg:g").selectAll("g.link")
    .data(force.links())
  .enter().append('g')
    .attr('class', 'link');

var linkPath = link.append("svg:path")
    .attr("class", function(d) { return "link " + d.type; })
    .attr("marker-end", function(d) { return "url(#" + d.type + ")"; });

var textPath = link.append("svg:path")
    .attr("id", function(d) { return d.source.index + "_" + d.target.index; })
    .attr("class", "textpath");

Now you have a separate path you can manipulate properly. As you noticed, there are two issues - you have to change the path direction, and you have to change the arc direction. It looks like you can do this in the path command string by swapping the sweep-flag value (see docs), so instead of Arx,ry 0 0,1 you have Arx,ry 0 0,0. You can reduce some code duplication by having one function to create path strings:

function arcPath(leftHand, d) {
    var start = leftHand ? d.source : d.target,
        end = leftHand ? d.target : d.source,
        dx = end.x - start.x,
        dy = end.y - start.y,
        dr = Math.sqrt(dx * dx + dy * dy),
        sweep = leftHand ? 0 : 1;
    return "M" + start.x + "," + start.y + "A" + dr + "," + dr +
        " 0 0," + sweep + " " + end.x + "," + end.y;
}

Then you can update the link path and the text path separately:

linkPath.attr("d", function(d) {
    return arcPath(false, d);
});

textPath.attr("d", function(d) {
    return arcPath(d.source.x < d.target.x, d);
});

See working code: http://jsfiddle.net/nrabinowitz/VYaGg/2/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!