Created
January 21, 2020 12:43
-
-
Save LeaveNhA/26d015e7b823b0e247c5a62225579576 to your computer and use it in GitHub Desktop.
D3 Zoomable Circle Packing with Label Line-Wrap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://observablehq.com/@d3/zoomable-circle-packing | |
// Zoomable Circle Packing lack of line wrapping in Labels. | |
// With the help of https://bl.ocks.org/mbostock/7555321 | |
// Now it has line wrapping. | |
// ----------------------------- After the zoom call ----------------------- | |
function wrap(text, width) { | |
text.each(function() { | |
var text = d3.select(this), | |
words = text.text().split(/\s+/).reverse(), | |
word, | |
wordCount = 0, | |
line = [], | |
lineNumber = 0, | |
lineHeight = 1.1, // ems | |
y = text.attr("y") !== null ? text.attr('y') : 0, | |
dy = text.attr("dy") !== null ? parseFloat(text.attr("dy")) : 0, | |
tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em"); | |
console.info(text.attr("y")); | |
while (word = words.pop()) { | |
line.push(word); | |
tspan.text(line.join(" ")); | |
if (wordCount++ >= 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); | |
wordCount = 0; | |
} | |
} | |
}); | |
} | |
svg.selectAll('text').call(wrap, 2); | |
// ------------------------------------------------------------------------------------------------ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment