简体   繁体   中英

Resizable rectangles for nodes in D3 collapsible tree

I modified the collapsible tree example to use rectangles instead of circles.

https://plnkr.co/edit/UKUufJItPQqIKH8DBGLx?p=preview

My question is how to get the rectangle heights to resize themselves depending on the text of the nodes. If you'll notice that the top node has overflowing text while the size of the

I'm aware of .getBBox() and the canonical wrap example but as I'm still newish to D3, I'm wondering how to bring it all together to get it to work.

Canonical 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
        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'; });  

Using 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'; });

Plunker: https://plnkr.co/edit/KtSfKp8mpwnMXElfpC9r?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM