Skip to content

Instantly share code, notes, and snippets.

@jkappers
Created October 15, 2012 15:06
Show Gist options
  • Save jkappers/3892971 to your computer and use it in GitHub Desktop.
Save jkappers/3892971 to your computer and use it in GitHub Desktop.
Force line wrapping in SVG text tags
(function() {
var svgns = "http://www.w3.org/2000/svg";
function forceTextWrappingOn(node, width) {
console.log(node);
var chars = node.firstChild.nodeValue.split(' '),
x = parseInt(node.getAttribute('x'), 10),
y = parseInt(node.getAttribute('y'), 10),
index = 0,
tspan, tspanWidth, textNode
node.removeChild(node.firstChild);
for (var c in chars) {
if (chars.hasOwnProperty(c)) {
tspanWidth = tspan == null ? 0 : tspan.getComputedTextLength();
if (tspanWidth > width || tspanWidth === 0) {
y = y + 20;
tspan = document.createElementNS(svgns, 'tspan');
tspan.setAttribute('x', x);
tspan.setAttribute('y', y);
node.appendChild(tspan);
index = 0;
}
textNode = document.createTextNode(index === 0 ? chars[c] : " " + chars[c]);
tspan.appendChild(textNode);
index++;
}
}
}
})();​
<svg id="svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<text x="100" y="100">This text is really long isn't it!</text>
</svg>​
<script>
var textNodes = document.querySelectorAll('text');
for (var n in textNodes)
if (textNodes.hasOwnProperty(n))
forceTextWrappingOn(textNodes[n], 50);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment