Created
February 24, 2012 05:39
-
-
Save ralphholzmann/1898054 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
// 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"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@ralphholzmann OH, I totally missed the
'SomeWebFont'
declaration... I blame sleepiness, woke up 15 minutes ago. :) Well done!