我正在尝试在 d3 中换行文本,我已经阅读过相关内容,并且我知道在 d3 中执行此操作的方法是将长文本分隔成插入到 tspan
elmenets 或将文本添加到 foreignObject
元素。
我正在尝试使用 tspan
方法来调整此函数
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,
y = text.attr("y"),
x = text.attr("x"),
dy = text.attr("dy"),
dx = text.attr("dx"),
tspan = text
.text(null)
.append("tspan")
.attr("x", x)
.attr("y", y)
.attr("dx", dx)
.attr("dy", dy);
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("dx", dx)
.attr("dy", ++lineNumber * lineHeight + Math.abs(dy) + "em")
.text(word);
}
}
});
}
该函数工作正常,但文本元素的dx
和dy
中定义的坐标丢失,导致文本出现在图形中的错误位置。
我已经通过将 .attr("dy",++lineNumber * lineHeight + Math.abs(dy) +"em ")
行替换为 .attr("来确定这一点dy", dy)
文本放置在所需位置,但 tspan
元素重叠。
得到这个
我对 d3 的概念很陌生,感谢您的评论
更新 1:调用函数 wrap
后分布 tspan 元素
<g class="category">
<circle r="15" cx="112.58330249197704" cy="64.99999999999997"></circle>
<text x="112.58330249197704" y="64.99999999999997" dx="20" dy="10" text-anchor="start">
<tspan x="112.58330249197704" y="64.99999999999997" dx="20" dy="10"></tspan>
<tspan x="112.58330249197704" y="64.99999999999997" dx="20" dy="11">Third</tspan>
<tspan x="112.58330249197704" y="64.99999999999997" dx="20" dy="11">Bit</tspan>
<tspan x="112.58330249197704" y="64.99999999999997" dx="20" dy="11">Category</tspan>
</text>
</g>
更新2:应用更新函数后的图形状态、文本分布详细信息
最佳答案
我已经使用此功能一段时间了,可能也适合您(可能需要稍作调整):
function wrap(text, width) {
text.each(function () {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1,
y = text.attr("y"),
x = text.attr("x"),
dy = 0,
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", lineHeight + "em").text(word);
lineHeight++;
}
}
});
}
更新:看起来我复制了错误的函数,我的项目中有多个版本。我相信这个应该可以正常工作。
您的函数与我共享的第一个函数存在相同的问题 - 我们都没有在循环中增加 lineHeight
(在您的情况下,它称为 lineNumber
)。
关于javascript - 关于如何调整在 d3 中换行文本的函数的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58382926/