Skip to content

Instantly share code, notes, and snippets.

@souporserious
Created January 21, 2019 20:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save souporserious/0eeb4d6a1f342fa8362f85f0a13602de to your computer and use it in GitHub Desktop.
Save souporserious/0eeb4d6a1f342fa8362f85f0a13602de to your computer and use it in GitHub Desktop.
Get the width for a single line of text
/**
* Get the width for a single line of text
* @param {String} text - the string of text to be measured
* @param {Object|HTMLElement} font - optional font styles or node to pull font styles from
* @return {Number} the width of the text passed in
*/
const expando = 'text-width' + new Date().getTime()
const canvas =
typeof document === 'undefined' ? null : document.createElement('canvas')
const context = canvas && canvas.getContext('2d')
const fontDefaults = {
fontStyle: 'normal',
fontVariant: 'normal',
fontWeight: 'normal',
fontSize: 'medium',
fontFamily: 'sans-serif',
}
function getTextWidth(text, font) {
if (!context) {
return -1
}
if (font instanceof HTMLElement) {
font = font[expando] || (font[expando] = getComputedStyle(font))
} else {
font = { ...fontDefaults, ...font }
}
context.font = [
font.fontStyle,
font.fontVariant,
font.fontWeight,
font.fontSize,
font.fontFamily,
].join(' ')
return context.measureText(text).width
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment