Last active
December 17, 2015 21:29
-
-
Save WebReflection/5675201 to your computer and use it in GitHub Desktop.
knows if the browser supports already a font family
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
| // 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)); |
AS toDataURL() & getImageData() are quite expensive, any chance to make use of measureText()?
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
Clever use of
toDataURL. This Modernizr detect does something similar, but usesgetImageDatainstead: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/emoji.js