gpt4 book ai didi

javascript - 在 SVG 动态树中标记节点的最佳解决方案(使用 D3.js)

转载 作者:行者123 更新时间:2023-11-29 10:20:25 25 4
gpt4 key购买 nike

我试图通过向每个节点添加特定标签(SVG 文本)来修改此 D3.js 示例 ( Dynamic Node-Link Tree),但没有成功。

如果我理解正确,在简要查看 SVG 规范和 D3 文档后,最好的方法是创建 SVG 组并移动它们。

不幸的是,这不起作用,因为转换对组没有影响。有没有我不知道的简单方法?

非常感谢。

最佳答案

如果您正在寻找将圆圈切换为文本标签的效果,您可以执行以下操作:

// Enter any new nodes at the parent's previous position.
node.enter().append("svg:text")
.attr("class", "node")
.attr("x", function(d) { return d.parent.data.x0; })
.attr("y", function(d) { return d.parent.data.y0; })
.attr("text-anchor", "middle")
.text(function(d) { return "Node "+(nodeCount++); })
.transition()
.duration(duration)
.attr("x", x)
.attr("y", y);

在这里查看 fiddle :http://jsfiddle.net/mccannf/pcwMa/4/

编辑

但是,如果您想在圆圈旁边添加标签,我不建议在这种情况下使用 svg:g,因为那样您就必须使用 transforms 移动组。相反,只需在更新函数中像这样在圆形节点和文本节点上加倍:

  // Update the nodes…
var cnode = vis.selectAll("circle.node")
.data(nodes, nodeId);

cnode.enter().append("svg:circle")
.attr("class", "node")
.attr("r", 3.5)
.attr("cx", function(d) { return d.parent.data.x0; })
.attr("cy", function(d) { return d.parent.data.y0; })
.transition()
.duration(duration)
.attr("cx", x)
.attr("cy", y);

var tnode = vis.selectAll("text.node")
.data(nodes, nodeId);

tnode.enter().append("svg:text")
.attr("class", "node")
.text(function(d) { return "Node "+(nodeCount++); })
.attr("x", function(d) { return d.parent.data.x0; })
.attr("y", function(d) { return d.parent.data.y0; })
.transition()
.duration(duration)
.attr("x", x)
.attr("y", y);

// Transition nodes to their new position.
cnode.transition()
.duration(duration)
.attr("cx", x)
.attr("cy", y);

tnode.transition()
.duration(duration)
.attr("x", x)
.attr("y", y)
.attr("dx", 4)
.attr("dy", 4); //padding-left and padding-top

可在此处找到证明这一点的 fiddle :http://jsfiddle.net/mccannf/8ny7w/19/

关于javascript - 在 SVG 动态树中标记节点的最佳解决方案(使用 D3.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13324189/

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