d3 可缩放树图 - 每个父宽度的动态文本宽度

d3 Zoomable Treemap - Dynamic Text Width per Parent Width

我正在使用找到的树状图模板 here.

按照目前的情况,我对代码做了一些修改,以便能够显示更多信息以及包含 运行 长的描述的文本换行。为此,我将以下 ptexttspan 标签替换为 foreignObjectxhtml:div 标签,如下所示:

已替换

var t = g.append("text")
    .attr("class", "ptext")
    .attr("dy", ".75em")

t.append("tspan")
    .text(function(d) { return d.key; });
t.append("tspan")
    .attr("dy", "1.0em")
    .text(function(d) { return formatNumber(d.value); });
t.call(text);

var t = g.append("foreignObject")
    .attr("class", "foreignobj");

t.append("xhtml:div")
    .html(function (d) {
        if (d.status != null) return "<p>Name: " + d.key + "</p>";
        else return d.key;
    })
    .attr("class", "textdiv");

t.append("xhtml:div")
    .html(function (d) {
        if (d.status != null) return "<p>Status: " + d.status + "</p>";
        else return "";
    })
    .attr("class", "textdiv");

t.append("xhtml:div")
    .html(function (d) {
        if (d.description != null) return "<p>Description: " + d.description + "</p>";
        else return "";
    })
    .attr("class", "textdiv");

所以现在文本可以换行了,但是foreignObject的宽度不等于父的宽度,所以文本区域很小并且与其他区域重叠<rect> name/status/description 足够长且文本换行的区域。

我尝试为 foreignObject 添加一个基于父项高度的属性,但这会导致不正确的宽度,我假设是在渲染早期从子节点中拉出的树状图。

var t = g.append("foreignObject")
                .attr("class", "foreignobj")
                .attr("width", $(this).parent().attr("width"));

我也试过找到最接近的 <rect> 标签并从中拉出宽度,获得 outerWidth,以及其他一些尝试都无济于事。

我想知道如何将 foreignObject 的宽度设置为等于父级的宽度,以便文本仅在框的边缘换行?

我可以通过更改脚本底部 text() 函数中的以下代码来解决这个问题:

function text(text) {
    text.selectAll("foreignobj")
        .attr("x", function(d) { return x(d.x) + 6; });
    text.attr("x", function(d) { return x(d.x) + 6; })
        .attr("y", function(d) { return y(d.y) + 6; })
        // Added the following line
        .attr("width", function(d) { return x(d.x + d.dx) - x(d.x) - 6; });
}