Last active
April 20, 2017 07:53
-
-
Save netsi1964/00a384b1626fad0f467b81cb0fcba435 to your computer and use it in GitHub Desktop.
flowText - a function to add flowing text to SVG
This file contains 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
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