Skip to content

Instantly share code, notes, and snippets.

@netsi1964
Last active April 20, 2017 07:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save netsi1964/00a384b1626fad0f467b81cb0fcba435 to your computer and use it in GitHub Desktop.
Save netsi1964/00a384b1626fad0f467b81cb0fcba435 to your computer and use it in GitHub Desktop.
flowText - a function to add flowing text to SVG
function flowText(text, svg, width, style) {
svg.innerHTML = "";
width = width - style.padding.left;
var svgText = document.createElementNS("http://www.w3.org/2000/svg", "text");
var textNode = document.createTextNode("");
svgText.appendChild(textNode);
var testElement = svg.appendChild(svgText);
var words = text.split(" ");
var len = 0,
start = 0,
count = 0,
part = "",
y = style.padding.top,
x = style.padding.left,
lineHeight = 0,
bbox,
last;
do {
last = start
do {
count++;
part = words.slice(start, count).join(" ");
testElement.innerHTML = part;
bbox = testElement.getBBox();
len = bbox.width;
lineHeight = bbox.height;
} while (count <= words.length && len < width && len !== 0);
count--;
y += lineHeight
part = words.slice(start, count).join(" ");
addText(part, x, y)
start = count;
} while (start != last);
testElement.remove()
if (start != words.length) {
part = words.slice(start, words.length).join(" ");
addText(part, x, y)
}
function addText(text, x, y) {
if (text.length === 0) return false;
var line = document.createElementNS("http://www.w3.org/2000/svg", "text");
var lineText = document.createTextNode(text);
line.setAttribute('x', x + 'px');
line.setAttribute('y', y + 'px');
line.appendChild(lineText);
svg.appendChild(line);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment