首页 > 解决方案 > 在 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)节点的内容被刷新,就好像它从未被包装过一样。

为什么会发生这种情况?欢迎任何想法。

标签: javascriptd3.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只包含空字符串。


推荐阅读