Created
March 4, 2010 08:43
-
-
Save harthur/321545 to your computer and use it in GitHub Desktop.
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
function getFont(element) { | |
// create canvas in owner doc to get @font-face fonts | |
var doc = element.ownerDocument; | |
var canvas = doc.createElement("canvas"); | |
var context = canvas.getContext("2d"); | |
if(!context.measureText) | |
return "Text"; | |
var style = doc.defaultView.getComputedStyle(element, null); | |
var fonts = style.fontFamily.split(','); | |
for(var i = 0; i < fonts.length; i++) | |
if(testFont(fonts[i], context)) | |
return fonts[i]; | |
return "serif"; | |
} | |
function testFont(font, context) { | |
var testString = "abcdefghijklmnopqrstuvwxyz"; | |
context.font = "400px serif"; | |
var defaultWidth = context.measureText(testString).width; | |
context.font = "400px " + font; | |
var fontWidth = context.measureText(testString).width; | |
if(defaultWidth == fontWidth) | |
return false; | |
return true; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment