Last active
October 23, 2020 08:43
-
-
Save gubser/a0a26d029b9c73341e44ca390c720298 to your computer and use it in GitHub Desktop.
Compute width of SVG text using DOM
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
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