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'; });
Mit 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
Das ist genial! Wie würde ich dies ändern, so dass die Breite fest ist, aber die Höhe des Rechtecks ändert sich? Ich habe naiv versucht, 'Breite' mit 'Höhe' zu tauschen, wo es möglich ist und leider war es nicht so einfach. – tehawtness