Skip to content

Instantly share code, notes, and snippets.

@ralphholzmann
Created February 24, 2012 05:39
Show Gist options
  • Save ralphholzmann/1898054 to your computer and use it in GitHub Desktop.
Save ralphholzmann/1898054 to your computer and use it in GitHub Desktop.
// This script exploits the fact that if you draw text on a
// canvas with a font stack that contains no available fonts,
// nothing gets drawn at all. So create a font stack with a
// single web font, and we can determine when it has been loaded.
var webfontCallback = (function() {
// Create a detached canvas with 1x1 dimensions
var canvas = document.createElement("canvas"),
context;
canvas.width = 1;
canvas.height = 1;
context = canvas.getContext("2d");
// Setup context with your webfont at a huge size (1000px),
// and a black fill style
$.extend( context, {
textAlign : 'center',
textBaseline: 'middle',
fillStyle : "#000000",
font : 'normal 1000px "SomeWebFont"' // The web font you're loading
});
return function( callback ) {
// Fill the canvas with black
context.fillRect( 0, 0, 1, 1 )
// Change fill style to white
context.fillStyle = "#ffffff";
// Render a huge 1000px X in the center of your canvas
context.fillText( "X", 0, 0 );
// See if the center-most pixel is still black
if ( context.getImageData(0, 0, 1, 1).data[0] === 0 ) {
// Reset fill style back to black and loop
context.fillStyle = "#000000";
setTimeout(function() {
fire( callback );
}, 0);
} else {
// Pixel isn't black, therefore the font has loaded,
// fire the callback
callback();
}
}
}());
webfontCallback( function() {
console.log("SomeWebFont is loaded and ready to be used");
});
@csnover
Copy link

csnover commented Feb 24, 2012

Just in case anyone else wonders:
Q: why 40px?
A: no reason really

@ralphholzmann
Copy link
Author

Updated to use a 1x1 canvas, instead of 40x40, as per @csnover. =)

@peol
Copy link

peol commented Feb 24, 2012

So, canvas elements can't be used before all web fonts has been loaded?

@ralphholzmann
Copy link
Author

@peol - not quite. I added a comment to the top of the function. Basically, if you try and render text on a canvas with a font that is not available to the browser, nothing gets rendered at all, so we can test for when a font is available by checking the color of a pixel after attempting to render text.

@peol
Copy link

peol commented Feb 24, 2012

@ralphholzmann OH, I totally missed the 'SomeWebFont' declaration... I blame sleepiness, woke up 15 minutes ago. :) Well done!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment