2017-03-02 145 views
1

我正在使用D3可视化一个力布局网络,并且我在沿节点之间的边缘定位箭头时遇到问题。正如您在图片中看到的,我根据每个节点的属性值缩放了我的节点的大小。基本上我需要某种方法来动态计算/更改我的箭头在我的边缘上的位置(根据用于缩放节点的相同值),以使它们可见并防止它们与节点重叠。其实我想让我的箭头“触摸”我节点的外边缘。有没有人有办法做到这一点?这些代码片段显示了我如何创建我的箭头。也许我应该用另一种方式?D3 SVG在路径上定位箭头

p.s.我知道我可以改变我的绘图顺序来绘制我的节点顶部的箭头,但那不是我想要的。

enter image description here

... 

svg.append("defs").append("marker") 
.attr("id", "arrowhead") 
.attr("refX", 5) /*must be smarter way to calculate shift*/ 
.attr("refY", 2) 
.attr("markerWidth", 6) 
.attr("markerHeight", 4) 
.attr("orient", "auto") 
.append("path") 
    .attr("d", "M 0,0 V 4 L6,2 Z"); 

... 

path.enter() 
     .append("svg:path") 
     .attr("class", function (d) { 
      return "link " + d.type; 
     }) 
     .attr("id", function (d) { 
      return "path_" + d.id; 
     }) 
     .attr("marker-end", "url(#arrowhead)") 
     .transition().duration(8000) 
     .style("stroke-width", stylePathStrokeWidth) 
... 
+0

您必须在defs中为每个路径动态构建一个箭头标记,并调整每个圆半径的refX。 –

+1

看到这个[回答我给了这里](http://stackoverflow.com/questions/41226734/align-marker-on-node-edges-d3-force-layout/41229068#41229068) – Mark

+0

@Mark谢谢你的帮助! –

回答

1

我解决了基于马克的回答这个问题Align Marker on node edges D3 Force Layout问题。这是我在tick函数中的代码:

function tick() { 

// fit path like you've been doing 
path.attr("d", function (d, i) { 
    dr = 550/d.linknum; 
    var result = "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y; 
    return result; 
}); 

// recalculate and back off the distance 
path.attr("d", function (d, i) { 
    var pl = this.getTotalLength(); 
    //this is the magic 
    var r = d.target.size + 3 * d.size; // Multiply the marker size (3) with the size of the edge (d.size) because the markers are scaling with the edge which they are attached to!! 
    var m = this.getPointAtLength(pl - r); 
    dr = 550/d.linknum; 
    var result = "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + m.x + "," + m.y; 
    return result; 
});