使用 Javascript 连接 SVG 圆圈

Connect SVG circles using Javascript

我正在尝试通过在源圆和目标矩形之间画线来连接 SVG 圆和矩形。这是我的 json 文件的格式:

    [{"sourceNode":"1","type":"sourceNode"},
     {"sourceNode":"3","type":"sourceNode"},
     {"sourceNode":"8","type":"sourceNode"},
     .....
     {"targetNode":"1","type":"targetNode"},
     {"targetNode":"7","type":"targetNode"},
     {"targetNode":"1","type":"targetNode"},
     .....
     {"type":"link","source":"1","target":"2"},
     {"type":"link","source":"3","target":"4"},
     {"type":"link","source":"3","target":"5"}]

我正在使用刻度函数为圆和线赋予属性。圆圈工作得很好,但是当我在 html 中检查我的 SVG 时,我没有得到没有属性的线。

这是代码:

var nodeSource = g.selectAll("circle")
    .data(data.filter(function (d){ return d.type == "sourceNode"; }))
    .enter().append("circle")
    .attr("r", 5)
    .style("fill", "blue")
        .call(force.drag);

 var nodeTarget = g.selectAll("rect")
    .data(data.filter(function (d){ return d.type == "targetNode"; }))
    .enter().append("rect")
    .attr("width", 10)
    .attr("height", 10)
    .style("fill", "green")
        .call(force.drag);

    var link = g.selectAll("line")
    .data(data.filter(function (d){ return d.type == "link"; }))
    .enter().append("line")
        .style("stroke-width", "2")
        .style("stroke", "grey")
        .call(force.drag);

function tick(e) {
    nodeSource
      .attr("cx", function(d) { return d.x = Math.max(radius(), Math.min(width() - radius(), d.x)); })
      .attr("cy", function(d) { return d.y = Math.max(radius(), Math.min(height() - radius(), d.y)); });

    nodeTarget
      .attr("x", function(d) { return d.x = Math.max(radius(), Math.min(width() - radius(), d.x)); })
      .attr("y", function(d) { return d.y = Math.max(radius(), Math.min(height() - radius(), d.y)); });

    link
      .attr("x1", function(d) { return d.source.x; })
      .attr("y1", function(d) { return d.source.y; })   
      .attr("x2", function(d) { return d.target.x; })
      .attr("y2", function(d) { return d.target.y; });

         chart.draw()

}

当您为直线分配 x1x2 等坐标时,实际上并没有给它们赋值。在您的 json 文件中,链接数据具有:

"source": "1"

例如。使用 d.source.anything 不会 return 一个值,因为 "1" 没有附加任何属性。如果你想获得对具有此编号的节点的引用,你必须使用 d3 来找到它:

line.attr('x1', function (d) {
        return d3.selectAll('circle').filter(function (k) {
            return d.source === k.sourceNode;
        }).attr('cx');
    })

然后,当你想做目标节点时:

line.attr('x2', function(d) {
        return d3.selectAll('rect').filter(function (k) {
            return d.target === k.targetNode;
        }).attr('x');
    })