动态添加节点到 d3.js 力向图

Mik*_*ike 3 javascript d3.js

我在动态添加节点到 d3.js 强制定向图时遇到问题,我想知道这里是否有人可以阐明这个主题。

我遇到的问题是我希望刻度函数能够转换图表上的所有节点,而不仅仅是新添加的节点。

以下是我用于添加节点和处理转换的函数:

// Function to handle tick event
function tick() {
     tick_path.attr("d", function(d) {
     var dx = d.target.x - d.source.x,
     dy = d.target.y - d.source.y,
     dr = Math.sqrt(dx * dx + dy * dy);
    return "M" + 
        d.source.x + "," + 
        d.source.y + "L" + 
        d.target.x + "," + 
        d.target.y;
     });

     tick_node.attr("transform", function(d) { 
          return "translate(" + d.x + "," + d.y + ")"; });
 }


 /**
   * Append nodes to graph.
   */
 function addNodes2Graph(){

    // define the nodes
       // selection will return none in the first insert
       // enter() removes duplicates (assigning nodes = nodes.enter() returns only the non-duplicates)
    var nodes = viz.selectAll(".node") 
    .data(g_nodes)
    .enter().append("g") 
    .on("click", nodeClick)
    .call(force.drag);

    // From here on, only non-duplicates are left
    nodes
        .append("circle")
        .attr("r", 12)
        .attr("class", "node");

    nodes.append("svg:image")
    .attr("class", "circle")
    .attr("xlink:href", "img/computer.svg")
    .attr("x", "-8px")
    .attr("y", "-8px")
    .attr("width", "16px")
    .attr("height", "16px");

   // add the text 
    nodes.append("text")
    .attr("x", 12)
    .attr("dy", ".35em")
        .text(function(d) { return d.ip; });


     return nodes;
 }

 // Execution (snippet)

 // Add new nodes
 tick_node = addNodes2Graph();
 // Add new paths
 tick_path = addPaths2Graph();


 // Restart graph
 force
.nodes(g_nodes) // g_nodes is an array which stores unique nodes
.links(g_edges) // g_edges stores unique edges
.size([width, height])
.gravity(0.05)
.charge(-700)
.friction(0.3)
.linkDistance(150)
.on("tick", tick)
.start();
Run Code Online (Sandbox Code Playgroud)

我认为问题是我只得到从 addNodes2Graph 返回的非重复结果,然后我在函数中使用tick它,但我不确定如何在不向图表添加重复节点的情况下实现这一目标。

目前,它要么将重复的元素添加到图表中,要么仅转换 上的新节点tick

非常感谢您提前提供的帮助。

Lar*_*off 5

看起来您只是将节点添加到 DOM,而不是强制布局。回顾一下,将节点添加到力布局中需要执行以下操作。

  • 将元素添加到力布局用于其节点的数组中。这需要与您最初传入的数组相同,即如果您想要平滑的行为,则无法创建新数组并传递它。修改force.nodes()应该可以正常工作。
  • 对链接执行相同的操作。
  • .data().enter()使用新数据添加新的 DOM 元素。
  • 不需要对函数进行任何更改tick,因为添加节点和 DOM 元素是在其他地方完成的。

添加新节点/链接后,您需要force.start()再次调用以使其考虑它们。