首页 > 解决方案 > D3 强制布局逐步更新

问题描述

我已经调整了D3 强制布局示例,并通过在计时器上加载(缓慢更改)数据使其动态化

      var inter = setInterval(function() {
        d3.json("http://localhost:5000/my_data", drawGraph);
      }, 5000);

这一切都有效,但图表每 5 秒从起始位置重新绘制一次,这在视觉上会分散注意力。实际上,从一次迭代到下一次迭代几乎没有变化,我希望图表从之前的位置重新开始布局。显然,当添加一个节点时,图形布局会发生变化;但我希望尽量减少视觉干扰,因为添加一个节点不应该在图中引起这么多的移动。

我怎样才能做到这一点?

我已经尝试保存并重新加载图形节点的位置,但这并没有做任何事情。我应该保存并重新加载代表节点的 SVG 对象的位置吗?(在我的情况下:圆圈。)或者我可以设置模拟开始移动节点的初始位置吗?

  // Load the positions of the nodes, assuming they are available at this point
  graph.nodes.forEach(function(o, i) {
    if (nodePos.has(o.id)) {
      o.x = nodePos.get(o.id).x
      o.y = nodePos.get(o.id).y
      console.log("< node " + o.id + ":" + o.x + "," + o.y)
    }
  });

  // Compute the layout
  var layout = d3.layout.force() // ... code omitted
  drawLinks(graph.links);
  drawNodes(graph.nodes);
  
  // ...

  // Save the positions of the nodes, assuming they are final at this point
  graph.nodes.forEach(function(o, i) {
        nodePos.set(o.id, {'x': o.x, 'y': o.y});
        console.log("> node " + o.id + ":" + o.x + "," + o.y)
      });

标签: javascriptd3.jsforce-layout

解决方案


推荐阅读