使用D3.js对文本进行换行和垂直居中



我有一个D3.js树映射,里面有一些标签。问题是有些文本太长了,放不进盒子里,所以我不得不把它们包起来。我采用了这个答案中提供的功能,包装效果很好。但是,当标签有多行时,文本不会垂直居中。

到目前为止,我的解决方案是用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");
}

最新更新