在d3.js中包装长文本

时间:2015-03-19 12:32:16

标签: svg d3.js

我想将长文本元素包装到宽度。这里的例子取自Bostock's wrap function,但似乎有两个问题:首先,wrap的结果没有继承元素的x值(文本向左​​移动);其次它包装在同一行上,lineHeight参数无效。

感谢建议。 http://jsfiddle.net/geotheory/bk87ja3g/

var svg = d3.select("body").append("svg")
    .attr("width", 300)
    .attr("height", 300)
    .style("background-color", '#ddd');

dat = ["Ukip has peaked, but no one wants to admit it - Nigel Farage now resembles every other politician", 
       "Ashley Judd isn't alone: most women who talk about sport on Twitter face abuse",
       "I'm on list to be a Mars One astronaut - but I won't see the red planet"];

svg.selectAll("text").data(dat).enter().append("text")
    .attr('x', 25)
    .attr('y', function(d, i){ return 30 + i * 90; })
    .text(function(d){ return d; })
    .call(wrap, 250);

function wrap(text, width) {
    text.each(function() {
        var text = d3.select(this),
        words = text.text().split(/\s+/).reverse(),
        word,
        line = [],
        lineNumber = 1,
        lineHeight = 1.2, // ems
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy")),
        tspan = text.text(null).append("tspan").attr("x", 0).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", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
            }
        }
    });
}

2 个答案:

答案 0 :(得分:3)

Bostock的原始函数假定text元素具有初始dy集。它还会删除x上的所有text属性。最后,您将wrap函数更改为从lineNumber = 1开始,需要0

重构一下:

function wrap(text, width) {
    text.each(function() {
        var text = d3.select(this),
        words = text.text().split(/\s+/).reverse(),
        word,
        line = [],
        lineNumber = 0, //<-- 0!
        lineHeight = 1.2, // ems
        x = text.attr("x"), //<-- include the x!
        y = text.attr("y"),
        dy = text.attr("dy") ? text.attr("dy") : 0; //<-- null check
        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);
            }
        }
    });
}

更新了fiddle

答案 1 :(得分:3)

问题在于这一行:

dy = parseFloat(text.attr("dy"))

在您已关联的示例中,dy设置在text元素上,但不在您的情况下。因此,您获得了NaN,从而导致dy的{​​{1}}为tspan。如果NaN

,则将{0}分配给dy进行修复
NaN

完整演示here