使用 D3.js 环绕和垂直居中文本
Wrapping and vertically centering text using D3.js
我有一个 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");
}
});
}
已经看到类似的 但答案中提供的垂直居中不适合我的用例。
我意识到我使用的是行数 - 1,而不仅仅是行数。删除 -1 解决了问题。
if (lineNumber > 0) {
const startDy = -(lineNumber * (lineHeight / 2)); // here was the issue
text
.selectAll("tspan")
.attr("dy", (d, i) => startDy + lineHeight * i + "em");
}
我有一个 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");
}
});
}
已经看到类似的
我意识到我使用的是行数 - 1,而不仅仅是行数。删除 -1 解决了问题。
if (lineNumber > 0) {
const startDy = -(lineNumber * (lineHeight / 2)); // here was the issue
text
.selectAll("tspan")
.attr("dy", (d, i) => startDy + lineHeight * i + "em");
}