Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active December 17, 2015 21:29
Show Gist options
  • Select an option

  • Save WebReflection/5675201 to your computer and use it in GitHub Desktop.

Select an option

Save WebReflection/5675201 to your computer and use it in GitHub Desktop.
knows if the browser supports already a font family
// example: if(!isFontSupported('Batang')) { ... }
// example: if(!isFontSupported('"Andale Mono"')) { ... }
var isFontSupported = (function(document){
// WebReflection - WTFPL License
var
defaultFamily = getComputedStyle(
document.documentElement, null
).getPropertyValue('font-family'),
defaultDataURL = '',
str = ['0123456789', 'abcdefghijklmnopqrstuvwxyz', defaultDataURL],
fontSize = 16,
width = str[1].length * fontSize,
height = 3 * fontSize,
i = 0,
withoutDefault = true,
canvas = document.createElement('canvas'),
context = canvas.getContext('2d');
str[2] = str[1].toUpperCase();
context.textBaseline = 'top';
function isFontSupported(fontFamily) {
canvas.width = width;
canvas.height = height;
context.clearRect(0, 0, width, height);
context.font = fontSize + "px " + (fontFamily || defaultFamily);
for(i = 0; i < 3; context.fillText(str[i], 0, ++i * fontSize));
if (withoutDefault) {
withoutDefault = !withoutDefault;
defaultDataURL = canvas.toDataURL();
}
return fontFamily === defaultFamily ||
defaultDataURL !== canvas.toDataURL();
}
isFontSupported();
return isFontSupported;
}(document));
@mathiasbynens

Copy link
Copy Markdown

Clever use of toDataURL. This Modernizr detect does something similar, but uses getImageData instead: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/emoji.js

@kekscom

kekscom commented May 30, 2013

Copy link
Copy Markdown

AS toDataURL() & getImageData() are quite expensive, any chance to make use of measureText()?

@WebReflection

Copy link
Copy Markdown
Author

@kekscom this is most likely a one shot check but measureText does not give you visual differences only size differences. @mathiasbynens didn't know modernizr was already doing in this way but getImageData might be a better choice since toDataURL is not supported that much (while I guess getImageData is) - not sure which one is faster though

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment