我有以下函式,用于在D3中包裝文本,取自這個答案:
function wrap(text, width) {
text.each(function() {
var text = d3.select(this)。
word = text.text().split(s /).reverse()。
字。
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"/span>, x)
.attr("y", y)
.attr("dy", dy "em")。
while (word = words.pop() ) {
line.push(word)。
tspan.text(line.join(" "/span>))。
if (tspan.node().getComputedTextLength() > width) {
line.pop()。
tspan.text(line.join(" "/span>))。
line = [word];
tspan = text.append("tspan")
.attr("x"/span>, x)
.attr("y", y)
.attr("dy", lineNumber * lineHeight dy "em")
.text(word)。
}
}
});
}
我以如下方式初始化節點:
我以如下方式初始化節點:
const nodes = [ 1, 2, 3]
const nodesTextsEnter = vis.g.selectAll('text').'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) =>/span> i*30)
.attr('y', (d, i) => i*30)
.attr('text-anchor', 'mid')
.attr('dominant-baseline'/span>, 'middle')
.attr('font-size', 12)
.style('cursor', 'pointer')
.attr('class', 'node')
.attr('opacity', '0')
.transition()
.attr('opacity', '1')
.attr('x', (d, i) =>/span> i*30)
.attr('y', (d, i) =>/span> i*30)
.text('this is a long text')
.call(wrap, 30)
編碼更新(nodesTextsUpdate
.transition(transitionDuration)
.attr('x', (d, i) =>/span> i*30)
.attr('y', (d, i) =>/span> i*30)
.text('this is a long text')
.call(wrap, 30)
問題是,在除錯wrap函式時,我看到所有的包裹變化都發生在節點上,但在某些時候(具體來說,我認為它發生在timer.js的wake函式中的timerFlush()),節點的內容被重繪 ,好像它從未被包裹過。
為什么會出現這種情況?任何想法都歡迎。
uj5u.com熱心網友回復:
如果你在過渡之前設定文本內容,你的代碼就可以作業了:
nodesTextsEnter.append('text'/span>)
.attr('x', (d, i) =>/span> i*30)
.attr('y', (d, i) =>/span> i*30)
.attr('text-anchor', 'mid')
.attr('dominant-baseline'/span>, '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'/span>, '1')
.attr('x', (d, i) =>/span> i*30)
.attr('y', (d, i) => i*30)
.call(wrap, 30)。
否則,d3.select(this).text()在wrap中的值是空的,因此words只包含空字串。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/320662.html
標籤:
