2016-10-07 8 views
0

collapsible tree exampleを変更して、円の代わりに矩形を使用しました。D3折りたたみツリー内のノードのサイズ変更可能な矩形

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

私の質問は、ノードのテキストに応じて、自分自身のサイズを変更するには、矩形の高さを取得する方法です。

私はgetBBox()とcanonical wrap exampleを認識していますが、まだD3には新しくなっているので、すべてそれを働かせるために一緒に。

答えて

1

Canonicalのラップ

getBBox()を使用して
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'; }); 

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

+0

これは素晴らしいです!幅を固定し、矩形の高さのサイズを変更するには、これをどのように変更しますか?私は当然のことながら、「幅」と「高さ」を入れ替えようとしましたが、残念ながらそれほど単純ではありませんでした。 – tehawtness

関連する問題