Skip to content

Instantly share code, notes, and snippets.

@josdejong
Created October 9, 2025 12:05
Show Gist options
  • Save josdejong/75e21602772c27178172e5e7f0be905d to your computer and use it in GitHub Desktop.
Save josdejong/75e21602772c27178172e5e7f0be905d to your computer and use it in GitHub Desktop.
A JavaScript function to test whether a font is supported or not
/**
* Usage:
*
* detectFont('arial') // true
*/
function detectFont(fontName: string) : boolean {
const canvas = window.document.createElement('canvas')
const context = canvas.getContext('2d')
const text = 'i' // this text has a different width for monospace and sans-serif
context.font = `16px ${fontName}, monospace`
const width1 = context.measureText(text).width
context.font = `16px ${fontName}, sans-serif`
const width2 = context.measureText(text).width
// if fontName is supported and is applied, the widths will be the same
// otherwise, we get the two widths of monospace and sans-serif, which differ from each other
return width1 === width2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment