javascript - 在 D3 中应用包装功能后,文本被刷新到初始状态
问题描述
我有以下用于在 D3 中包装文本的函数,取自这个答案:
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
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);
}
}
});
}
我以以下方式初始化节点:
const nodes = [1, 2, 3]
const nodesTextsEnter = vis.g.selectAll('text.node').data(nodes).enter()
const nodesTextsUpdate = vis.g.selectAll('text.node').data(nodes)
vis.g.selectAll('text.node').data(nodes).exit().remove()
nodesTextsEnter.append('text')
.attr('x', (d, i) => i*30)
.attr('y', (d, i) => i*30)
.attr('text-anchor', 'middle')
.attr('dominant-baseline', 'middle')
.attr('font-size', 12)
.style('cursor', 'pointer')
.attr('class', 'node')
.attr('opacity', '0')
.transition()
.attr('opacity', '1')
.attr('x', (d, i) => i*30)
.attr('y', (d, i) => i*30)
.text('This is a long text')
.call(wrap, 30)
nodesTextsUpdate
.transition(transitionDuration)
.attr('x', (d, i) => i*30)
.attr('y', (d, i) => i*30)
.text('This is a long text')
.call(wrap, 30)
问题是,在调试wrap
函数时,我看到节点上发生了所有包装更改,但是在某些时候(特别是,我认为它发生timerFlush()
在wake
函数中timer.js
)节点的内容被刷新,就好像它从未被包装过一样。
为什么会发生这种情况?欢迎任何想法。
解决方案
如果您在转换之前设置文本内容,您的代码将起作用:
nodesTextsEnter.append('text')
.attr('x', (d, i) => i*30)
.attr('y', (d, i) => i*30)
.attr('text-anchor', 'middle')
.attr('dominant-baseline', 'middle')
.attr('font-size', 12)
.style('cursor', 'pointer')
.attr('class', 'node')
.attr('opacity', '0')
.text('This is a long text') // this line was moved up
.transition()
.attr('opacity', '1')
.attr('x', (d, i) => i*30)
.attr('y', (d, i) => i*30)
.call(wrap, 30);
否则,d3.select(this).text()
in的wrap
值为空,因此words
只包含空字符串。
推荐阅读
- javascript - 有没有办法检测用户离开后何时返回您的网页?
- odoo - 在 one2many odoo 12 中获取默认值
- python - 如何动态定义`typing.Union`?
- jquery - Angular 7 - 数据表 - 上传按钮
- mongodb - 更新嵌套数组文档上的一个字段
- javascript - 如何在函数 JSDoc 中使用 @template 来创建参数和返回类型之间的一致性?
- python - python中运行平均值的简单程序产生超出范围的索引
- windows - pyinstaller--onefile创建exe后,程序中的wav文件只在创建exe文件的电脑上播放
- php - 使用 foreach 循环分配 postdata 变量
- javascript - WordPress中的砌体