Skip to content

Instantly share code, notes, and snippets.

@jrue
Created December 7, 2018 03:36
Show Gist options
  • Save jrue/ce9f05010b6de30bad1ea05f6dfa30b6 to your computer and use it in GitHub Desktop.
Save jrue/ce9f05010b6de30bad1ea05f6dfa30b6 to your computer and use it in GitHub Desktop.
D3 Multiline Labels
d3.selection.prototype.wrappedText = function(width) {
this.each(function(d) {
var text = d3.select(this);
if(text.text() === ""){ return this; }
var words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr("y"),
x = text.attr("x"),
dy = 0;
var tspan = text.text(null).append("tspan").attr("x", x).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width(d)) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", x).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
};
//example
bubbles.append("text")
.attr("x", function(d){ return d.x; })
.attr("y", function(d){ return d.y + 5; })
.attr("text-anchor", "middle")
.text(function(d){ return d.data["Name"]; })
.style("fill","white")
.style("font-family", "san-serif")
.style("font-size", "10px")
.wrappedText(function(d){ return d.r * 2; }); //radius of bubble
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment