我正在使用d3.js强制控制图。它具有连接它们的节点和链接。要创建箭头,我将svg和d3结合使用,如下所示:
gA.svg.append('defs').selectAll('marker').data(['arrow-head']) // binding 'arrow-head' is our way of attaching a name!
.enter().append('marker')
.classed('arrow-head', true)
.attr({
id: String,
viewBox: '0 -5 10 10',
refX: 24, // this controls the distance of the arrowhead from the end of the line segment!
refY: 0,
markerWidth: 5,
markerHeight: 5,
orient: 'auto',
})
.append('path')
.attr('d', 'M0,-5L10,0L0,5')
要将那个箭头附加到每个边缘/链接的末端,我要做:
let link = gA.svg.selectAll('.link').data(gA.force.links(), link => gA.node_id(link.source) + '--->' + gA.node_id(link.target)) // links before nodes so that lines in SVG appear *under* nodes
link.enter().append('line')
.classed('link', true)
.attr('marker-end', 'url(#arrow-head)') // add in the marker-end defined above
link.exit().remove()
使箭头到线段末端的距离可变的最佳方法是什么?这样做的目的是使箭头位于每个节点圆的边缘,而不是位于节点中间。最好不要为每个可能的距离分别设置SVG定义:)
我在想类似的东西:
.attr('marker-end', var_arrow_head)
function var_arrow_head(link){
radius = link.target.radius
refX = 2 + 5*radius
magically get an altered version of arrow-head with the new refX value
return 'url(#magic-arrow-head)'
}
最佳答案
似乎您希望将标记放置在每行的末尾,但是节点的半径是可变的。在这种情况下,我建议您在defs
中使用单个标记定义,并仅根据可变节点半径更新链接的长度。
此stackoverflow问题包含可能的答案-linking nodes of variable radius with arrows