可调整大小的矩形节点在D3折叠树

Resizable rectangles for nodes in D3 collapsible tree

本文关键字:D3 折叠 节点 可调整      更新时间:2023-09-26

我修改了可折叠树的例子,用矩形代替圆形。

<代码> https://plnkr.co/edit/UKUufJItPQqIKH8DBGLx?p =

预览

我的问题是如何根据节点的文本来调整矩形高度。如果你注意到顶部节点有溢出的文本而

的大小

我知道。getbbox()和规范的包装的例子,但因为我仍然是新手D3,我想知道如何把它放在一起,让它的工作。

规范包装:

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
        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);
      }
    }
  });
}
nodeHeight = 40, nodeWidth = 150;
nodeUpdate.selectAll("text").call(wrap,nodeWidth);
nodeUpdate.select('rect')
    .attr('rx', 6)
    .attr('ry', 6)
    .attr('y', -(nodeHeight / 2))
    .attr('width', nodeWidth)
    .attr('height', nodeHeight)
    .style('fill', function(d) { return d._children ? 'lightsteelblue' : '#fff'; });  
使用getBBox ()

:

nodeUpdate.select('rect')
    .attr('rx', 6)
    .attr('ry', 6)
    .attr('y', -(nodeHeight / 2))
    .attr('width', function(d){
      var textElement = d3.select(this.parentNode).select("text").node();
      var bbox = textElement.getBBox();
      var width = bbox.width;
      return width*2;
    })
    .attr('height', nodeHeight)
    .style('fill', function(d) { return d._children ? 'lightsteelblue' : '#fff'; });

砰砰作响:https://plnkr.co/edit/KtSfKp8mpwnMXElfpC9r?p=preview