Badass JavaScript

A showcase of awesome JavaScript that pushes the boundaries of what's possible on the web, by @devongovett.

Font.js: A Powerful Font Toolkit for JavaScript

January 23rd 2012

Mike Kamermans has been working on a little font toolkit for your JavaScript that is kind of akin to the built-in Image object but for Fonts.  It gives you font loading events using a technique perfected in Mozilla’s pdf.js project, metrics information, and a better version of the canvas element’s measureText method with additional information such as height, bounding box, and leading.

A demo of the library shows that it’s pretty similar to the built in Image object in terms of usage.  Here’s an example:

var font = new Font();
font.onload = function() {
    // measure some text
    console.log(font.measureText("some text", 14));
    
    // style an element
    document.querySelector("p").style.fontFamily = "'" + font.fontFamily + "'";
}

font.onerror = function(e) {
   alert(e);
}

// kick off the actual loading
font.fontFamily = "My Font";
font.src = "acmesa.ttf";

Feels right at home - a very nice API indeed!  It works by downloading the font data with an AJAX request, parsing out some metadata to determine that it is indeed a valid font file and to pull out the metrics information.  Then it inserts an @font-face rule into the page and a test DIV and polls the width of that DIV until it is no longer zero-width at which point it can determine that the browser has loaded the font and it is ready for use.  Finally it calls your onload handler.  See how much work you’re avoiding? :)

You check out the source on Github, and a demo here.  Enjoy!