首页 > web前端 > css教程 > 正文

如何在 D3 树可视化中包装文本标签以提高可读性?

Susan Sarandon
发布: 2024-10-25 01:10:02
原创
723 人浏览过

How can I wrap text labels in a D3 tree visualization for improved readability?

在 D3 树中包裹文本

在 D3 树可视化中,有时需要将文本标签包裹在节点上以使树更具可读性。本文演示了如何实现这种文本换行。

挑战

考虑以下 D3 树:

Foo is not a long word
登录后复制

理想情况下,文本应该换行为:

Foo is
not a
long word
登录后复制

解决方案

要实现文本换行,需要进行两个关键修改:

  1. 创建换行函数:

    实现换行函数,添加 元素节点并控制环绕宽度:

    <code class="javascript">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);
                }
            }
        });
    }</code>
    登录后复制
  2. 使用环绕函数:

    不要在每个节点上设置文本,而是应用换行函数:

    <code class="javascript">// Add entering nodes in the parent’s old position.
    node.enter().append("text")
        .attr("class", "node")
        .attr("x", function (d) { return d.parent.px; })
        .attr("y", function (d) { return d.parent.py; })
        .text("Foo is not a long word")
        .call(wrap, 30); // wrap the text in <= 30 pixels</code>
    登录后复制

通过实现这些修改,您可以成功地在 D3 树节点上换行文本。

以上是如何在 D3 树可视化中包装文本标签以提高可读性?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!