【问题标题】:D3 Wordwrap with data-driven width limit具有数据驱动宽度限制的 D3 Wordwrap
【发布时间】:2015-06-21 01:33:14
【问题描述】:

在 D3 中创建一些文本并自动换行非常简单:

var textElement = svg.selectAll('text')
                   .data(myData)
                   .enter()
                   .append('text')
                   .text(someVeryLongText)
                   .call(wrapText, allowedWidth);

wrapText() 函数是使用相当标准的示例之一实现的(例如http://bl.ocks.org/mbostock/7555321)。

我遇到的问题是,当我想让每个文本字段的允许宽度取决于数据时,例如:

                   ...
                   .text(someVeryLongText)
                   .call(wrapText, function(d) {
                     return d.someCondition ? 100 : 200;
                   });

这样的事情可能吗?

【问题讨论】:

    标签: javascript text d3.js


    【解决方案1】:

    如下所示调整您链接的示例中的 wrap 函数,并在您的帖子中使用所需的调用签名。工作示例here

    function wrap(text, width) {
        text.each(function(d, i/*[edit]*/) {
            var text = d3.select(this),
                words = text.text().split(/\s+/).reverse(),
                word,
                line = [],
                lineNumber = 0,
                lineHeight = 1.1, // 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"),
                //[edit]add dWidth
                dWidth = typeof width === "function" ? width(d, i) : width;
            while (word = words.pop()) {
                line.push(word);
                tspan.text(line.join(" "));
                if (tspan.node().getComputedTextLength() > dWidth/*[edit]*/) {
                    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);
                }
            }
        });
    }
    

    【讨论】:

    • 请记住,在当前的形式中,如果已经有 tspan 元素,它将中断。但如果你稍微调整一下,就很容易修复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 2017-10-17
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    相关资源
    最近更新 更多