首頁 > web前端 > css教學 > 主體

如何在 D3 中換行文字以提高樹視覺化的可讀性?

Barbara Streisand
發布: 2024-10-25 07:43:02
原創
590 人瀏覽過

How can I wrap text in D3 to improve the readability of my tree visualizations?

在 D3 中換行文字

增強 D3 樹的可讀性可以涉及換行文字以防止長單字扭曲版面。這可以透過使用來實現。元素,它允許在單一文字區塊中創建多行。

要實現文字換行,請依照以下步驟操作:

1.建立包裝函數

基於Mike Bostock 的「包裝長標籤」範例,定義一個名為wrap 的函數,該函數會加入根據指定寬度將元素加入文字節點:

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);
            }
        }
    });
}
登入後複製

2.應用文字換行

不要直接設定每個節點的文本,而是利用換行功能將文本換行到指定寬度內:

// 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);
登入後複製

這會將文本換行30 像素,根據需要創建多行以容納長單字。

以上是如何在 D3 中換行文字以提高樹視覺化的可讀性?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!