Draw an arrow between two circles?

后端 未结 4 1062
再見小時候
再見小時候 2021-02-10 07:31

How can I draw an arrowed line between two circles, given:

  1. Location of the centers of the cirlces
  2. Radius of the circles

I am using

4条回答
  •  一生所求
    2021-02-10 08:14

    I had the same issue and here's how I solved it. Changes made to the original fiddle:

    Change .attr("refX", 27) to .attr("refX", 0). This makes the arrowhead draw beyond the end of the line.

    Compute the proper ending positions of the lines using trigonometry, accounting for arrowheads, by adding the following code to "tick":

    var arrowheadLength = 8, // from markerWidth
        nodeRadius = 10;
    link.each(function(d) {
      var x1 = d.source.x,
          y1 = d.source.y,
          x2 = d.target.x,
          y2 = d.target.y,
          angle = Math.atan2(y2 - y1, x2 - x1);
      d.targetX = x2 - Math.cos(angle) * (nodeRadius + arrowheadLength);
      d.targetY = y2 - Math.sin(angle) * (nodeRadius + arrowheadLength);
    });
    

    Use the computed targetX and targetY link properties:

    .attr("x2", function(d){
      return d.targetX;
    }).attr("y2", function(d){
      return d.targetY;
    })
    

    Here is the updated fiddle.

提交回复
热议问题