【问题标题】:D3 v4: Node position set to NaND3 v4:节点位置设置为 NaN
【发布时间】:2017-01-12 23:08:17
【问题描述】:

这可能是有史以来最简单的 D3 力布局:

const svg = main.append("svg")
    .attr("width",500)
    .attr("height",500)
    .classed("SVG_frame",true)
    .append("g")

const nodes = [{id:1},{id:2}];

const simulation = d3.forceSimulation(nodes)
    .force("centering",d3.forceCenter([200,200]))
    .force("collision",d3.forceCollide(20))

const node = svg
    .selectAll("circle")
    .data(nodes)
    .enter().append("circle")
    .attr("r",20)

simulation.on("tick",function() {
    console.log(nodes[0].x)
    node
        .attr("cx",d => d.x)
        .attr("cy",d => d.y)
})

然而,我在第一帧得到<circle> attribute cx: Expected length, "NaN".。 (cy 在模拟放弃移动的框架上移动了一点点)

我知道这个问题已经被问过好几次了,但似乎没有一个解决版本 4,其中力模拟可能已经改变了它的内部运作。事实上,文档现在甚至声明当位置为 NaN 时,the position is automatically arranged in a "phyllotaxis arrangement" or whatever,所以也许这不应该发生,但它确实发生了。

有人知道吗?

【问题讨论】:

    标签: javascript d3.js


    【解决方案1】:

    这里的问题很简单:d3.forceCenter 接受两个值,而不是值数组:

    [d3.forceCenter] 使用指定的 x 和 y 坐标创建新的定心力。如果未指定 x 和 y,则默认为 ⟨0,0⟩。

    在 API 中,参数周围的括号表示该参数是可选的 (see here)。当您在 D3 API 中看到这样的内容时:

    d3.forceCenter([x, y])

    您必须注意不要将这些括号误认为是数组。这里,[x, y] 表示这些值是可选的,并不意味着它们必须在数组中。

    所以,而不是:

    .force("centering",d3.forceCenter([200,200]))
    

    应该是:

    .force("centering",d3.forceCenter(200,200))
    

    这是一个演示:

    const svg = d3.select("body").append("svg")
        .attr("width",500)
        .attr("height",500)
        .classed("SVG_frame",true)
        .append("g")
    
    const nodes = [{id:1},{id:2}];
    
    const simulation = d3.forceSimulation(nodes)
        .force("centering",d3.forceCenter(200,200))
        .force("collision",d3.forceCollide(20))
    
    const node = svg
        .selectAll("circle")
        .data(nodes)
        .enter().append("circle")
        .attr("r",20);
    
    simulation.on("tick",function() {
        node.attr("cx",d => d.x).attr("cy",d => d.y)
    });
    <script src="https://d3js.org/d3.v4.min.js"></script>

    【讨论】:

    • AAAAAAAAAAAAAAAAAAAAA 你是对的!有效!我永远不知道这些括号是数组还是文档符号。这次我选择了前者。 :/ 我想我会假设它们永远不是数组,除非另​​有说明。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 2015-02-17
    • 1970-01-01
    • 2020-04-05
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    相关资源
    最近更新 更多