gpt4 book ai didi

javascript - 使 d3 v4 组对模拟使用react

转载 作者:行者123 更新时间:2023-12-03 03:35:26 25 4
gpt4 key购买 nike

jsfiddle https://jsfiddle.net/z7ju3z1q/3/

问题是,我无法通过工作模拟使标题与组保持一致。从simulation.nodes(nodes)更改第76行;到模拟.节点(节点); (显然)破坏了模拟,但使标题粘在圆圈上。据我了解,问题在于,出于某种原因,拖动与圆圈一起工作而不是与组一起工作。这就是我一整天都面临的问题。

我尝试像这样描述标题(第 38 行)

var title = g.selectAll("text");

然后将其添加到勾号(第 84 行)

function ticked() {
title.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
}

最佳答案

As I understand, the problem is that dragging working with circles but not with groups, for some reason

您正在使用 cx 和 cy 属性来操纵拖动时的节点。 g 元素没有这些,因此即使 node 包含组而不是圆圈,也不会实现您想要的效果:

  node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })

如前所述,node = g.append("circle") 意味着您实际上并未操作 g 元素,这就是您的圆圈继续移动的原因勾选或拖动。

相反,将节点保留为 g 元素的选择,并操作 transform 属性:

  // the group representing each node:
node = node.enter().append("g").merge(node);

// the circle for each group
node.append("circle")
.classed('node', true).attr('id', id)
.text(id)
.attr("r", 25).attr("fill", function(d) { return color(d.id); });

// the text for each group
node.append("text")
.classed('text', true)
.attr("text-anchor", "start")
.attr("dx", 6).text(id).merge(node);

然后,在单击或拖动事件时,只需更新变换即可:

打勾:

  node.attr("transform",function(d) { return "translate("+d.x+","+d.y+")" ;});

拖动:

  d.x = d3.event.x;
d.y = d3.event.y;
d3.select(this).attr("transform",function(d) { return "translate("+d.x+","+d.y+")" ;});

这是一个updated fiddle .

关于javascript - 使 d3 v4 组对模拟使用react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45884606/

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