Created
January 21, 2019 20:59
-
-
Save souporserious/0eeb4d6a1f342fa8362f85f0a13602de to your computer and use it in GitHub Desktop.
Get the width for a single line of text
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
/** | |
* 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