简体   繁体   English

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

[英]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 https://plnkr.co/edit/UKUufJItPQqIKIKH8DBGLx?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. 我知道.getBBox()和规范包装示例,但是由于我仍然不熟悉D3,所以我想知道如何将所有功能组合在一起以使其正常工作。

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() : 使用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 柱塞: https ://plnkr.co/edit/KtSfKp8mpwnMXElfpC9r p = preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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