【问题标题】:Connect SVG circles using Javascript使用 Javascript 连接 SVG 圆圈
【发布时间】:2017-12-23 15:31:42
【问题描述】:

我试图通过在源圆和目标矩形之间画线来连接 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()

}

【问题讨论】:

  • 你在使用强制布局吗?你给了 force.nodes() 什么?这似乎是 force.nodes 和 force.links 中缺少的参考

标签: javascript json d3.js svg visualization


【解决方案1】:

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

"source": "1"

例如。使用d.source.anything 不会返回值,因为"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');
    })

【讨论】:

    猜你喜欢
    • 2021-10-06
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 2015-10-19
    • 2015-06-09
    • 1970-01-01
    相关资源
    最近更新 更多