Align Marker on node edges D3 Force Layout

前端 未结 1 627
情深已故
情深已故 2020-11-28 11:53

I\'m trying to implement a d3 force layout and can\'t figure out how to position the markers of my links in a proper way.

Here is what I got so far:

         


        
1条回答
  •  鱼传尺愫
    2020-11-28 12:00

    Interesting question. This works by setting the link path normally, then recalculating the end position by backing off the length by the radius of the circle.

    First in the marker def, set the refX and refY to 0 (this is the current way it stays outside the circle):

      .attr("refX", 0)
      .attr("refY", 0)
    

    Then do:

    function tick() {
    
      // fit path like you've been doing
      path.attr("d", function(d){
        var dx = d.target.x - d.source.x,
            dy = d.target.y - d.source.y,
            dr = Math.sqrt(dx * dx + dy * dy);
        return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
      });
    
      // recalculate and back off the distance
      path.attr("d", function(d) {
    
        // length of current path
        var pl = this.getTotalLength(),
            // radius of circle plus marker head
            r = (d.target.weight) * 4 + 16.97, //16.97 is the "size" of the marker Math.sqrt(12**2 + 12 **2)
            // position close to where path intercepts circle
            m = this.getPointAtLength(pl - r);          
    
         var dx = m.x - d.source.x,
            dy = m.y - d.source.y,
            dr = Math.sqrt(dx * dx + dy * dy);
    
          return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + m.x + "," + m.y;
      });
    
      circle.attr("transform", transform);
      text.attr("transform", transform);
    }
    

    Running code:

    
    
    
    
      
      
    
    
    
      
    
    
    

    0 讨论(0)
提交回复
热议问题