d3 有向图编辑器添加

d3 Directed Graph Editor additions

我一直在尝试用一些想法来扩充 d3 Directed Graph Editor code,这将使它成为想要 "manually grow" 图表的人们非常直观的界面。我设法将节点 ID 更改为用户可以通过提示调用输入的字符串。将 "type" 值添加到连接节点的 link 也是如此。

我苦苦挣扎的部分是,当图形重绘时,我无法设法在 link 中间呈现 link 属性 "type"。有人可以提供 help/the 代码吗?

以下是设置示例节点和 links 的行:

var nodes = [
    {id: 'some name', reflexive: false},
    {id: 'some other name', reflexive: true },
    {id: 'some 3rd name', reflexive: false}
],
links = [
    {source: nodes[0], target: nodes[1], left: false, right: true ,type: 'some type I'},
    {source: nodes[1], target: nodes[2], left: false, right: true, type: 'some type II'}
];

当节点被渲染时,有一段代码将 id 添加为字符串:

g.append('svg:text')
    .attr('x', 0)
    .attr('y', 4)
    .attr('class', 'id')
    .text(function(d) { return d.id; });

然而,当 links 被重绘时,没有函数获取类型属性的值并在源节点和目标节点的坐标之间以 1/2 的方式解析它。据我所知,这是处理 links.

的代码
// update existing links
path.classed('selected', function(d) { return d === selected_link; })
    .style('marker-start', function(d) { return d.left ? 'url(#start-arrow)' : ''; })
    .style('marker-end', function(d) { return d.right ? 'url(#end-arrow)' : ''; });


// add new links
path.enter().append('svg:path')
    .attr('class', 'link')
    .classed('selected', function(d) { return d === selected_link; })
    .style('marker-start', function(d) { return d.left ? 'url(#start-arrow)' : ''; })
    .style('marker-end', function(d) { return d.right ? 'url(#end-arrow)' : ''; })
    .on('mousedown', function(d) {
        if(d3.event.ctrlKey) return;

        // select link
        mousedown_link = d;
        if(mousedown_link === selected_link) selected_link = null;
        else selected_link = mousedown_link;
        selected_node = null;
        restart();
    });

这里是link to a jsfiddle with the latest version of the code.

在您的刻度函数中,只需根据源和目标 xy 重新计算文本的 xy 位置:

 function tick() {
   d3.selectAll("text")
   .attr("x", function(d) {return (d.source.x + d.target.x) / 2})
   .attr("y", function(d) {return (d.source.y + d.target.y) / 2})
 }

这是带有路径标签的更新后的 jsFiddle: http://jsfiddle.net/rco31ofe/2/