我在本网站搜索了当前主题,但没有解决方案解决我的问题。
如何在 D3 圆形包装中为长文本显示两行文本。我正在使用以下代码在圆圈上显示标签:
const label = svg.append("g")
.style("font-weight", "bold")
.attr("pointer-events", "none")
.attr("text-anchor", "middle")
.selectAll("text")
.data(root.descendants())
.join("text")
.style("fill-opacity", d => d.parent === root ? 1 : 0)
.style("text-shadow", "0px 0px 11px #FFF")
.style("display", d => d.parent === root ? "inline" : "none")
.attr("dy", "0.3em")
.text(d => d.data.name);
SVG 没有内置的自动换行选项来自动分割长文本的行。Mike Bostock在https://bl.ocks.org/mbostock/7555321 中描述了一个换行功能,当您提供text
和width
属性时,它会将文本拆分为适当的行。
function 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
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);
}
}
});
}
您可以通过在选择上调用它来调用它,使用selectAll(".textclass").call(wrap,textwidth)
wheretextclass
是要换行的文本的类,textwidth
是允许的文本宽度。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句