【发布时间】:2016-08-17 18:48:34
【问题描述】:
这是我正在使用的代码:https://jsfiddle.net/eb2L618g/1/
我在使用 D3.js API 时遇到了问题,尤其是如何根据动态数据设置每个节点的 x 位置。特别是,当我更改节点的 x 位置时,连接源节点和目标节点的 path.links 没有正确更新,并且不再接触源节点和目标节点。首先,我偏移节点x位置:
我在更新函数中添加了这个:
// Enter any new nodes at the parent's previous position.
nodeEnter.append("rect")
.attr("y", -barHeight / 2)
// added this function to try to offset the x position
.attr("x", function(d){
return d.x +20 // hardcode offset for now
})
.attr("height", barHeight)
.attr("width", barWidth)
.style("fill", color)
.on("click", click);
上面的添加偏移了每个节点与其父节点的 x 位置,到目前为止还不错,但它破坏了其中文本的对齐方式,所以我添加了这个:
nodeEnter.append("text")
.attr("x", function(d){
return d.x +20
})
.attr("dy", 3.5)
.attr("dx", 5.5)
.text(function(d) { return d.name; });
但是现在 path.links 没有对齐:
...所以我一直在玩这部分代码:
// Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
})
.transition()
.duration(duration)
.attr("d", diagonal);
// Transition links to their new position.
link.transition()
.duration(duration)
.attr("d", diagonal);
我尝试更改对角函数的源值和目标值,但它似乎没有做任何事情。我遗漏了一些关于 path.links 如何与其源节点和目标节点对齐的信息。我正在查看 D3.js 文档,但想看看是否有人能指出我正确的方向或注意到上述代码中的任何缺陷或缺失的功能。
使用 D3.js 版本 3。
【问题讨论】:
标签: javascript d3.js