简体   繁体   中英

autosize node width for d3 tree layout

Please suggest on how to autosize the width of the node according the node value for d3 tree layout.

The following is the link reference I adapted and piece of code.

var margin = {
top: 20,
right: 120,
bottom: 20,
left: 120
},
width = 960 - margin.right - margin.left,
height = 800 - margin.top - margin.bottom;

http://jsfiddle.net/augburto/YMa2y/

I haven't answered your exact question, but essentially you to need to dynamically auto size the svg rectangle. I've updated your fiddle to dynamically sizing the rectangle based on the number of children, using this code:

> .attr("width", function (d,i) { if(d._children) console.log(rectW +
> d._children.length);
>         return d._children ? (rectW + d._children.length) : rectW; })

Which simply adds the length of the number of children to the rectW. For what you want to do you need to calculate the length of the text and set that to the width of the rectangle. This question might help you calculate the length of the text. You'll also have to recalculate the centre of the rectangle to place the label.

Hope this gets you going.

Cheers

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