我正在尝试更改每个path
,以便它们从每个矩形的右侧开始并连接到左侧。目前他们似乎正在旅行"通过"矩形并在矩形内的某处有一个起点/终点,而不是补偿rect
的大小。
我试过操作这段代码:
var diagonal = d3.svg.diagonal()
.source(function (d) { return { "x": d.source.y, "y": d.source.x }; })
.target(function (d) { return { "x": d.target.y - 10, "y": d.target.x }; })
.projection(function (d) { return [d.y + 0, d.x + 0];
});
但这只是以灾难告终,但我相信答案就在那边。
这是脚本的JSFiddle,它位于http://jsfiddle.net/ra26wnbb/。
更新 我查看了D3 tree square node not in desired position,但我不确定它是否适用于我的文本包装。
答案 0 :(得分:2)
首先,在完成wrap()
内的工作后,您需要将结果高度存储在文本的基准面上:d.height = 19 * (lineNumber + 1);
。这样,高度就可以满足任何需要。例如,您可以使用它来设置rect
之外的wrap()
高度,而不是parentNode.children[0]
,这样可以更好地分离关注点。无论如何,这是wrap()
最终的结果:
function wrap(text, width) {
text.each(function (d) { // DIFF add param d
var text = d3.select(this),
// DIFF: use datum to get name, instead of element text
words = d.name.split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
// DIFF: store the height via the datum, d
d.height = 19 * (lineNumber + 1);
d3.select(this.parentNode.children[0]).attr('height', 19 * (lineNumber + 1));
});
}
});
现在你有了d.height
,你可以用它来计算对角线端点的必要偏移量。
// calculate source and target offsets
// d.height gets set by the wrap() function
var diagonal = d3.svg.diagonal()
.source(function (d) {
return {
"x": d.source.x + d.source.height / 2,
"y": d.source.y + 150
};
})
.target(function (d) {
return {
"x": d.target.x + d.target.height / 2,
"y": d.target.y
};
})
.projection(function (d) { return [d.y + 0, d.x + 0];
});