【问题标题】:Force directed graph stops being responsive强制有向图停止响应
【发布时间】:2017-10-23 11:47:52
【问题描述】:
var containerdiv = document.getElementById("container");
var svg = d3.select(containerdiv).append("svg")

// Extract the width and height that was computed by CSS.
var width = containerdiv.clientWidth;
var height = containerdiv.clientHeight;

var color = d3.scaleOrdinal(d3.schemeCategory20);

var simulation = d3.forceSimulation()
  .force("link", d3.forceLink().id(function(d) { return d.id; }))
  .force("charge", d3.forceManyBody())
  .force("center", d3.forceCenter(width/2, height/2));

function redraw(){

  console.log("window is being redrawn");

  width = containerdiv.clientWidth;
  height = containerdiv.clientHeight;

  simulation.force("center", d3.forceCenter(width/2, height/2));

  // Use the extracted size to set the size of an SVG element.
  svg
    .attr("width", width)
    .attr("height", height);

}

// Redraw based on the new size whenever the browser window is resized.
window.addEventListener("resize", redraw);

目前我正在尝试使用上面的代码获得一个响应式窗口。 forceSimulation 在停止响应窗口大小调整之前改变了它的中心几次。我有声明:console.log("window is being redrawn");,我知道CSS 每次调整窗口大小时都会检测到。但行为如下:

对函数redraw的初始调用


窗口大小调整工作


窗口大小调整已停止工作

【问题讨论】:

  • 尝试使用监听器:window.addEventListener("resize", redraw); 完全重新初始化您的 d3。 gl
  • @pirs 我忘了添加那行。你是什​​么意思:“完全重新初始化你的 d3.gl”
  • 你应该把你几乎所有的d3代码都放在redraw中,这样基本上会更稳定。
  • ^-- 不要那样做:这是不必要的,而且会降低性能。
  • @GerardoFurtado 我同意,我试过了,但它降低了性能。

标签: javascript css d3.js svg


【解决方案1】:

D3 模拟有一个内部计时器,并且在冷却之前只运行给定数量的滴答声(大约 300 个)。

因此,您必须使用restart() 重新加热模拟。根据 API,restart()

重新启动模拟的内部计时器并返回模拟。与simulation.alphaTarget 或simulation.alpha 结合使用,此方法可用于在交互过程中“重新加热”模拟,例如在拖动节点时,或在使用simulation.stop 暂时暂停后恢复模拟。

因此,您可以在 redraw 函数中执行此操作:

simulation.alpha(.8).restart();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-12
    • 2021-12-04
    • 1970-01-01
    相关资源
    最近更新 更多