gpt4 book ai didi

javascript - D3 forceX/forceY 和 forceCenter 的区别

转载 作者:行者123 更新时间:2023-11-30 20:12:51 24 4
gpt4 key购买 nike

我有以下代码:

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

这是一个示例 codePen(见第 57 行): https://codepen.io/anon/pen/PdOqZK?editors=1010

最后一行设置力中心。当我四处拖动节点并设置这个中心时,节点似乎从中心出去了。但是当我有以下内容时:

var simulation = d3v5.forceSimulation()
.force('link', d3v5.forceLink().id(function (d) { return d.id; }))
.force('charge', d3v5.forceManyBody())
.force('x', d3v5.forceX(width / 2))
.force('y', d3v5.forceY(height / 2))

这是一个示例 codePen(见第 57 行): https://codepen.io/anon/pen/gdXprR?editors=1010

它按预期工作。如果有人可以解释发生了什么,那就太好了。

最佳答案

两个 JSFiddle 的行为都是预期的。

这里的问题是 d3.forceCenterd3.forceX/Y不可可互换或类似的方法。 “居中”“定位”是不一样的,它们的用途和作用截然不同。

如果您查看 API,您会看到 d3.forceCenter...

...translates nodes uniformly so that the mean position of all nodes (the center of mass if all nodes have equal weight) is at the given position ⟨x,y⟩. (emphasis mine)

因此,这里的重要概念是“质心”。例如,当您将一个节点移动到右侧时,其他节点将移动到左侧,因此质心保持在指定位置。这种行为的效果是,如果将一个节点拖到 SVG 的边缘,其他节点将消失在对面。

另一方面,“定位”不会同时影响所有节点。正如关于 d3.forceX/Y 的 API 所述,

... while these forces can be used to position individual nodes... (emphasis mine)

关于javascript - D3 forceX/forceY 和 forceCenter 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52219671/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com