D3.js强制布局:动态添加的节点不随图形的其余部分移动

时间:2013-12-13 22:23:16

标签: javascript layout d3.js nodes force-layout

我正在使用Mike Bostock创建的原始示例在D3中构建分子创建者:http://bl.ocks.org/mbostock/3037015

我正在使用强制布局,就像在示例中一样。我的问题是当我动态添加一个新的Node / atom时,它不会随着图的其余部分移动。我已经阅读了其他问题并实现了所有建议并确保我遵循D3要求的正确更新/加入程序,但仍然添加的碳拒绝与图表的其余部分一起移动。

这是我的更新/创建功能:

function buildMolecule () {
    // Update link data
    link = link.data(links);

      // Create new links
    link.enter().append("g")
          .attr("class", "link")
          .each(function(d) {
            d3.select(this)
              .insert("line", ".node")
              .style("stroke-width", function(d) { return (d.bond * 2 - 1) * 2 + "px"; });

            d3.select(this)
              .filter(function(d) { return d.bond > 1; }).append("line")
              .attr("class", "separator");

            d3.select(this)
              .on("click", bondClicked);
    });

    // Delete removed links
    link.exit().remove();    

    // Update node data

    node = node.data(nodes);

    // Create new nodes
    node.enter().append("g")
          .attr("class", "node")
          .on("click", atomClicked)
          .each(function(d) {
            console.log('d:', d);
            // Add node circle
              d3.select(this)
                .append("circle")
                .attr("r", function(d) { return radius(d.size); })
                .style("fill", function(d) { return color(d.atom); });

            // Add atom symbol
              d3.select(this)
                .append("text")
                .attr("dy", ".35em")
                .attr("text-anchor", "middle")
                .text(function(d) { return d.atom; });

                d3.select(this).call(force.drag);
            });

      // Delete removed nodes
    node.exit().remove();

    force.start();
}

JsFiddle:http://jsfiddle.net/2dPMF/1/

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:3)

您正在修改节点和链接的数据结构,而不是添加和删除节点,这会影响力布局。我特别在谈论这些界限。

function bigBang () {
    links = links.concat(linksList);
    nodes = nodes.concat(nodesList);
    buildMolecule();
  }

该函数的前两行是我所说的。工作jsfiddle here