D3.jsを使用してこのジェネリック関数を使用すると、svg:text要素のテキストを複数のsvg:tspan子(1行に1つのtspan)にラップできます。
function wrapText(text, width) {
text.each(function () {
var textEl = d3.select(this),
words = textEl.text().split(/\s+/).reverse(),
word,
line = [],
linenumber = 0,
lineHeight = 1.1, // ems
y = textEl.attr('y'),
dx = parseFloat(textEl.attr('dx') || 0),
dy = parseFloat(textEl.attr('dy') || 0),
tspan = textEl.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 = textEl.append('tspan').attr('x', 0).attr('y', y).attr('dx', dx).attr('dy', ++linenumber * lineHeight + dy + 'em').text(word);
}
}
});
}
次のように使用できます。
svg.selectAll('text').call(wrapText, 100);