規範包裝:
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'; });
使用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
這是真棒!我將如何修改這個,使寬度固定,但矩形高度調整?我天真地嘗試在適用的情況下將「寬度」與「高度」互換,但不幸的是,這並不那麼簡單。 – tehawtness