Last active
December 14, 2015 06:09
-
-
Save b123400/5040263 to your computer and use it in GitHub Desktop.
Detect where a font is available.
Usage: isFontAvailable("Tahoma") //true
This file contains 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
var isFontAvailable; | |
(function(){ | |
var fontCanvas=null,fontCtx=null,cachedWidth={}; | |
isFontAvailable=function(fontFace){ | |
if(!fontCanvas){ | |
fontCanvas=document.createElement('canvas'); | |
fontCtx=fontCanvas.getContext('2d'); | |
} | |
var stringToMeasure="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"; | |
var fontsToTest=["monospace","sans-serif","serif"]; | |
for(var i=0,len=fontsToTest.length;i<len;i++){ | |
var thisTestFont=fontsToTest[i]; | |
var testWidth=cachedWidth[thisTestFont];//cached | |
if(!testWidth){ | |
fontCtx.font="72px "+thisTestFont; | |
testWidth=cachedWidth[thisTestFont]=fontCtx.measureText(stringToMeasure).width; | |
} | |
var finalWidth=cachedWidth[fontFace]; | |
if(!finalWidth){ | |
fontCtx.font="72px "+fontFace+","+thisTestFont; | |
finalWidth=fontCtx.measureText(stringToMeasure).width; | |
} | |
if(testWidth!=finalWidth){ | |
cachedWidth[fontFace]=finalWidth; | |
return true; | |
} | |
} | |
return false; | |
} | |
})(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment