【发布时间】:2019-10-14 19:23:48
【问题描述】:
我想在 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", dy) 替换.attr("dy", ++lineNumber * lineHeight + Math.abs(dy) +" em ") 行,文本被放置在所需位置,但tspan 元素重叠。
得到这个
我是 d3 概念的新手,我很欣赏你的 cmets
更新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:应用更新函数后的图形状态,文本分布细节
【问题讨论】:
标签: javascript d3.js