Skip to content

Instantly share code, notes, and snippets.

@sengiv
Created April 6, 2023 00:32
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 sengiv/6405283d798c19742596b4c353bed9f4 to your computer and use it in GitHub Desktop.
Save sengiv/6405283d798c19742596b4c353bed9f4 to your computer and use it in GitHub Desktop.
Input text converts to nicely formatted SVG box
//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