Created
October 9, 2025 12:05
-
-
Save josdejong/75e21602772c27178172e5e7f0be905d to your computer and use it in GitHub Desktop.
A JavaScript function to test whether a font is supported or not
This file contains hidden or 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
| /** | |
| * 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