Display an arrow head in the middle of D3 force layout link

前端 未结 3 1005
执笔经年
执笔经年 2020-12-01 08:26

I\'m using D3 to draw a force-directed graph, which is very similar to this example: http://bl.ocks.org/mbostock/1153292

I\'m trying to place the arrowheads in the m

3条回答
  •  忘掉有多难
    2020-12-01 08:57

    I'm the OP, this answer is just an addition to the excellent answers above for the sake of others with the same question.

    The answers show how to achieve this for a graph with arc links. If you have straight links, the accepted answer needs to be modified slightly. This is how:

    Your straight links are probably implemented with line, they need to be converted into polyline. Like so:

    // old: svg.selectAll(".link").data(links).enter().append("line")
    svg.selectAll(".link").data(links).enter().append("polyline")
    

    Then we have to encode the polyline according to this example, so your original code that encodes the line:

    force.on("tick", function() {
       link.attr("x1", function(d) {return d.source.x;})
           .attr("y1", function(d) {return d.source.y;})
           .attr("x2", function(d) {return d.target.x;})
           .attr("y2", function(d) {return d.target.y;});
    

    Changes into:

    force.on("tick", function() {
       link.attr("points", function(d) {
          return d.source.x + "," + d.source.y + " " + 
                 (d.source.x + d.target.x)/2 + "," + (d.source.y + d.target.y)/2 + " " +
                 d.target.x + "," + d.target.y; });
    

    And last, don't forget the convert marker-end to marker-mid:

    // old: link.attr("marker-end",
    link.attr("marker-mid",
    

    Credits to @Phrogz for showing the way.

提交回复
热议问题