Skip to content

Instantly share code, notes, and snippets.

@gubser
Last active October 23, 2020 08:43
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 gubser/a0a26d029b9c73341e44ca390c720298 to your computer and use it in GitHub Desktop.
Save gubser/a0a26d029b9c73341e44ca390c720298 to your computer and use it in GitHub Desktop.
Compute width of SVG text using DOM
export function computeTextLength(content: string, fontSize?: string) {
const svgns = "http://www.w3.org/2000/svg";
// create elements
const svg: SVGSVGElement = document.createElementNS(svgns, 'svg');
const text: SVGTextElement = document.createElementNS(svgns, 'text');
text.textContent = content;
if(fontSize) {
text.style.fontSize = fontSize;
}
// hook them into dom
document.getElementsByTagName('body')[0].appendChild(svg);
svg.appendChild(text);
// compute length
const length = text.getComputedTextLength();
// cleanup
svg.remove();
text.remove();
return length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment