简体   繁体   中英

draw a rectangle with custom texts around an image in d3 dendrogram

I am trying to draw a rectangle shape where I can fit some data in a d3 dendrogram. But I am not sure how I can do this. I have the initial plunkr available here: http://plnkr.co/edit/AoqY1xoRlwyK3VAxYuhz?p=preview Here is what I know I can do for appending text:

  nodeEnter.append("text")
      .attr("x", function(d) { return d.children || d._children ? -10 : 10; })
      .attr("dy", ".35em")
      .attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
      .text(function(d) { return d.name; })
      .style("fill-opacity", 1e-6);

Basically I want to draw a shape like this around every node: 在此处输入图片说明

Can anyone help me here or point me to some doc which I can refer for this.

You already have group elements here. That being said, all you need is to append your rectangles (don't mind the magic numbers here, you can change them later):

var nodeRect = nodeEnter.append("rect")
      .attr("height", 14)
      .style("fill", "dodgerblue")
      .attr("rx", 4)
      .attr("ry", 4)
      .attr("y", -7);

Then, after the text selection being created/appended, calculate the length of the texts. Here I'm using this.nextSibling.nextSibling because I know where the texts are in relation to the rectangles:

nodeRect.attr("width", function(d) {
        return this.nextSibling.nextSibling.getComputedTextLength() + 30
    })
    .attr("x", function(d, i) {
        return d._children || d.depth === 0 ? -(this.nextSibling.nextSibling.getComputedTextLength() + 14) : -14
    });

Here is your updated Plunker: http://plnkr.co/edit/a32rYZT6cSZ0c5zQrC6W?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