Created
January 26, 2017 13:31
-
-
Save nkint/89faff6d5c7c76d65c6e854c54db34db to your computer and use it in GitHub Desktop.
ES6 port of famous mbostock's word wrap for d3 SVG text label
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
// ES6 port of famous mbostock's word wrap https://bl.ocks.org/mbostock/7555321 | |
export function wrap(_text, width, lineHeightEm = 1.1) { | |
_text.each(function () { | |
const text = select(this) | |
const words = text.text().split(/\s+/).reverse() | |
const y = text.attr('y') | |
const dy = parseFloat(text.attr('dy')) || 0 | |
let tspan = text.text(null).append('tspan').attr('x', 0).attr('y', y).attr('dy', dy + 'em') | |
let line = [] | |
while (true) { | |
const word = words.pop() | |
if (!word) break | |
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', lineHeightEm + 'em') | |
.text(word) | |
} | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment