Skip to content

Instantly share code, notes, and snippets.

@harthur
Created March 4, 2010 08:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harthur/321545 to your computer and use it in GitHub Desktop.
Save harthur/321545 to your computer and use it in GitHub Desktop.
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