Skip to content

Instantly share code, notes, and snippets.

@unicornist
Last active November 16, 2020 02:15
Show Gist options
  • Save unicornist/992e915747a94d9e5142d76a909fc379 to your computer and use it in GitHub Desktop.
Save unicornist/992e915747a94d9e5142d76a909fc379 to your computer and use it in GitHub Desktop.
Detect actual browser font support via `Canvas`-based measurement
(function () {
const options = {
text: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789~!@#$%^&*()_+`-={}|[]\\:";\'<>?,./',
fontSize: 72,
baseFont: 'monospace'
}
this.checkFont = (input) => {
const fonts = (typeof input === 'string') ? input : (getComputedStyle(input).getPropertyValue('font-family') || input.style.fontFamily)
const ctx = document.createElement('canvas').getContext('2d')
const measureWidth = (...fonts) => {
ctx.font = options.fontSize + 'px ' + fonts
return ctx.measureText(options.text).width
}
return Object.fromEntries(fonts.split(',').map(f => [f.replace(/'|"/g, '').trim(),
measureWidth(options.baseFont) !== measureWidth(f, options.baseFont)
]))
}
})()

Detect actual browser font support via Canvas-based measurement

How to Use

Add the checkFont.js code to a page you want to detect a font within.

Calling checkFont('Font Names') or checkFont(anElement), returns an object telling which fonts are supported by this browser.

Examples

checkFont('MyFontFace, Roboto')
/* returns -> {
  "MyFontFace": false,
  "Roboto": false
} */

checkFont(document.body)
/* returns -> {
  "-apple-system": false,
  "BlinkMacSystemFont": false,
  "Segoe UI": true,
  "Roboto": false,
  "Noto Sans": false,
  "Ubuntu": false,
  "Droid Sans": false,
  "Helvetica Neue": false,
  "sans-serif": true
} */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment