【问题标题】:why doesn't D3.layout.force doesn't start properly?为什么 D3.layout.force 不能正常启动?
【发布时间】:2016-06-15 18:47:31
【问题描述】:

我正在使用 d3 的 layout.force 引擎为强制导向的图形布局创建图形。

有一段时间它可以工作,但现在当我执行start() 函数时,什么也没有发生。我已将我的代码精简为以下内容:

    var svg = d3.select("#field_d3").append("svg");
    var width = 720;
    var height = 640;
    svg.attr("width", width)
        .attr("height", height);
    var nodes = [
        {nid: "node1", x: width/2, y: height/2},
        {nid: "node2", x: width/2, y: height/2},
        {nid: "node3", x: width/2, y: height/2}
    ];

    var links = [
        { source: 0, target: 1},
        { source: 1, target: 2}];

    var force = d3.layout.force()
        .nodes(nodes)
        .links(links)
        .size([width, height])
        .linkStrength(0.9)
        .friction(0.9)
        .linkDistance(100)
        .charge(-30)
        .gravity(0.1)
        .alpha(0.2);

    console.log("Force layout initilized", force);
    force.on('end', function () {
        console.log("Force Layout calculations complete");
    });

    force.on('start', function () {
        console.log("Force layout started");
    });

    force.on('tick', function () {
        console.log("Force layout is ticking");
    });

    console.log("Starting force layout", force);
    force.start();
    //------------
    console.log("Now after all force layout code");

field_d3 是一个 id=field_d3 的 div。

但我在控制台中看到的只是

Force layout initilized Object {}
Starting force layout Object {}
Now after all force layout code

没有调用任何 start、end 或 tick 函数。 出了什么问题?

【问题讨论】:

  • @echonax 提供的 sn-p 是 minimal reproducible example 的一个很好的例子;它被精简到最低限度,并包含解决手头问题所需的所有代码。圆圈和线条只是计算值的图形表示,对于这个问题不是必需的。 tick() 函数也是如此,对于这个问题,它不需要比写日志更冗长。感谢@GreySage,他努力提供了一个很好的例子。尽管最好将其放入可执行的 Stack Snippet、JSFiddle 等中;-)
  • That 说,如果我将代码放在JSFiddle 中,它对我来说非常有效。来自starttickend 函数的所有日志都按预期打印。
  • @altocumulus 哦,对不起,我没有仔细阅读这个问题。我认为 OP 意味着屏幕上没有出现任何内容,但实际上是在询问力功能:)

标签: javascript d3.js force-layout


【解决方案1】:

您已经取消了设置宽度和高度的值,这会停止强制布局运行(它们都将是未定义的)。当您将它们重新插入时它会起作用。例如

var width = 500;
var height = 500;

http://jsfiddle.net/jw2z814e/

【讨论】:

  • 对不起,那是我的错。我实际上已经设置了这些变量,我只是没有将它包含在代码中,因为它比其他所有变量都高。我将编辑我的问题。
猜你喜欢
  • 2015-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-28
  • 1970-01-01
  • 1970-01-01
  • 2016-07-16
  • 2019-01-04
相关资源
最近更新 更多