Created
April 6, 2023 00:32
-
-
Save sengiv/6405283d798c19742596b4c353bed9f4 to your computer and use it in GitHub Desktop.
Input text converts to nicely formatted SVG box
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 | |
// This function attempts to create a new svg "text" element, chopping | |
// it up into "tspan" pieces, if the text is too long | |
static textToSvg(caption, x, y) { | |
//svg "text" element to hold smaller text lines | |
var svgTextHolder = document.createElementNS('http://www.w3.org/2000/svg', 'text'); | |
svgTextHolder.setAttributeNS(null, 'x', x); | |
svgTextHolder.setAttributeNS(null, 'y', y); | |
svgTextHolder.setAttributeNS(null, 'font-size', 10); | |
svgTextHolder.setAttributeNS(null, 'fill', '#FFF'); | |
svgTextHolder.setAttributeNS(null, 'text-anchor', 'left'); | |
//The following two variables can be passed as parameters | |
var maximumCharsPerLine = 30; | |
var lineHeight = 10; | |
var words = caption.split(" "); | |
var line = ""; | |
//process text and create rows | |
var svgTSpan; | |
var lineCount = 0; //number of lines to calculate height | |
var tSpanTextNode; | |
for (var n = 0; n < words.length; n++) { | |
var testLine = line + words[n] + " "; | |
if (testLine.length > maximumCharsPerLine) { | |
// Add a new <tspan> element | |
svgTSpan = document.createElementNS('http://www.w3.org/2000/svg', 'tspan'); | |
svgTSpan.setAttributeNS(null, 'x', x); | |
svgTSpan.setAttributeNS(null, 'y', y); | |
tSpanTextNode = document.createTextNode(line); | |
svgTSpan.appendChild(tSpanTextNode); | |
svgTextHolder.appendChild(svgTSpan); | |
line = words[n] + " "; | |
y += lineHeight; //place next text row lower | |
lineCount++; //count a line | |
} | |
else { | |
line = testLine; | |
} | |
} | |
//calculate final height in px, save global to be accessed later | |
window.EventDescriptionTextHeight = lineCount * lineHeight; | |
svgTSpan = document.createElementNS('http://www.w3.org/2000/svg', 'tspan'); | |
svgTSpan.setAttributeNS(null, 'x', x); | |
svgTSpan.setAttributeNS(null, 'y', y); | |
tSpanTextNode = document.createTextNode(line); | |
svgTSpan.appendChild(tSpanTextNode); | |
svgTextHolder.appendChild(svgTSpan); | |
return svgTextHolder; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment