【发布时间】:2020-06-18 20:21:32
【问题描述】:
我有一个 D3.js 树图,里面有一些标签。问题是某些文本太长而无法放入框内,因此我必须将它们包装起来。我采用了this answer 中提供的功能,并且包装效果很好。但是,当标签超过一行时,文本不会垂直居中。
到目前为止,我的解决方案是为dy 属性而不是0 以负值(对应于半行高乘以行数)开始第一行。虽然它使文本向框的顶部移动了一点点,但它仍然不是垂直居中的。
wrap(text, width) {
text.each(function() {
var text = d3.select(this),
words = text
.text()
.split(/\s+/)
.reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
x = text.attr("x"),
y = text.attr("y"),
dy = 0, //parseFloat(text.attr("dy")),
tspan = text
.text(null)
.append("tspan")
.attr("x", x)
.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", x)
.attr("y", y)
.attr("dy", ++lineNumber * lineHeight + dy + "em")
.text(word);
}
}
// this is my custom solution
if (lineNumber > 0) {
const startDy = -((lineNumber - 1) * (lineHeight / 2));
text
.selectAll("tspan")
.attr("dy", (d, i) => startDy + lineHeight * i + "em");
}
});
}
已经看到类似的question,但答案中提供的垂直居中不适合我的用例。
【问题讨论】:
-
您能否为您的工作实例创建一个 jsfiddle?
标签: javascript d3.js position