D3:当父母被拖入武力定向树时,如何阻止子节点被吸引到中心?
我已经使用D3.js V7构建了一个实力定向的树布局。到目前为止,它的工作正常,除了我甚至在可观察的示例中看到的行为 https ://observablehq.com/collection/@d3/d3-force
这就是我到目前为止所拥有的。
行为是,当我将一个节点拖到边缘时,孩子们似乎被吸引到中心。像这样:
我想像这样的“负载平衡”的子节点:
这是我设置模拟的方式:
const simulation = d3
.forceSimulation()
.force(
"link",
d3
.forceLink()
.id((d) => d.id)
.distance(100)
.strength(1)
)
.force("charge", d3.forceManyBody().strength(-500))
.force("x", d3.forceX())
.force("y", d3.forceY())
.alphaDecay(0.05);
simulation.on("tick", () => {
link
.attr("x1", (d) => d.source.x)
.attr("y1", (d) => d.source.y)
.attr("x2", (d) => d.target.x)
.attr("y2", (d) => d.target.y);
node.attr("transform", function (d) {
return "translate(" + d.x + "," + d.y + ")";
});
});
我为此创建了一个工作codepen 在这里让您与我在谈论的内容一起玩。
我尝试将节点和链接到不同的值更改,但它们并没有真正帮助。我还尝试过禁用Center
力量,但是如果我这样做的话,模拟永远不会出现在屏幕上。
.force("center").strength(0)
有没有办法实现我想要的东西?任何帮助都将受到赞赏。
I have built a force-directed tree layout using d3.js v7. It works fine so far except for a behavior that I've seen even in the examples on Observable https://observablehq.com/collection/@d3/d3-force
This is what I have so far.
The behavior is that when I drag a node towards the edge, the children seem to be attracted towards the center. Like so:
I'd like, instead, for the child nodes of "Load Balancing" to appear like this:
Here is how I've set up the simulation:
const simulation = d3
.forceSimulation()
.force(
"link",
d3
.forceLink()
.id((d) => d.id)
.distance(100)
.strength(1)
)
.force("charge", d3.forceManyBody().strength(-500))
.force("x", d3.forceX())
.force("y", d3.forceY())
.alphaDecay(0.05);
simulation.on("tick", () => {
link
.attr("x1", (d) => d.source.x)
.attr("y1", (d) => d.source.y)
.attr("x2", (d) => d.target.x)
.attr("y2", (d) => d.target.y);
node.attr("transform", function (d) {
return "translate(" + d.x + "," + d.y + ")";
});
});
I've created a working Codepen for this here for you to play around with what I'm talking about.
I've tried changing the node and link forces to different values but they didn't really help. I've also tried disabling the center
force but then the simulation never appears on the screen if I do that.
.force("center").strength(0)
Is there a way to achieve what I'm looking for? Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
控制其他节点行为的一种方法是将它们修复在拖动函数中。我在您的代码中添加了一个函数,以修复其他节点,并且不允许它们在拖动过程中移动。
One way to control the other nodes behavior is to fix them in the dragged function. I have added a function in your code, to fix other nodes and not allow them to move during drag.