Posts Tagged ‘fonts’

Font detection with Javascript and Flash

Thursday, June 26th, 2008

View the demo now

I was playing around with jquery and I wanted to see if it was possible to generate a cheat sheet of all the fonts on your system. Its also a good run through of how to load a SWF with a callback.

View a demo

The steps I used to generate this are:

  • Load SWF
  • Javascript calls to Actionscript fonts() method via ExternalInterface
  • Get the list of system fonts in Flash via Font.enumerateFonts(true)
  • Curse Flash for giving you a list of font names, where half of them are garbage.
  • For each font name, in javascript, create a test which adds a DOM element temporarily with a fallback font family set. For example, font-family: 'Apple Garamond Pro', 'Times New Roman';, where Times New Roman is your fallback.
  • Then check the actual width (via offsetWidth). If it does not match the offsetWidth of the fallback font, then we know it rendered ok. (The original idea is from http://www.lalit.org/lab/javascript-css-font-detect)

The only caveat is, if the actual font width and the fallback font width do match, then you would have a false negative. So its not bulletproof.

The actionscript to enumerate the fonts and call back out is pretty simple:

Expose the method in the constructor using ExternalInterface:

FontList.as

I used swfobject to load the SWF. Also be sure to enable allowScriptAccess.

The javascript to test the fonts is at: font-detect.js

You can use it by including:

 

In the end, I don’t think this is useful in practice, but I thought I would share anyway. Its on github too.

Updated: Now uses call straight to actionscript, doesn’t marshall JSON first so its much faster, and other refactoring.