Reputation: 813
I'm making something in canvas that uses fonts from a web service and what happens is that when the canvas is first loaded the fonts, which I'm loading from google fonts, haven't arrived yet so for the briefest of moments there's only plain font in the canvas and then it switches to my downloaded font.
This is a minor detail but very annoying. I'm wondering if theres any way to preload the fonts, i.e. not execute the canvas associated javascript code until after I'm sure I have the fonts already.
The font is placed in the header of the html:
<link href='https://fonts.googleapis.com/css?family=Stalinist+One' rel='stylesheet' type='text/css'>
and the js links at the bottom of the file, just before the closing of the body.
Upvotes: 1
Views: 353
Reputation: 105015
Use Google's WebFontLoader script
https://github.com/typekit/webfontloader
WebFontLoader's fontactive
callback is the equivalent of the img element's onload
.
WebFontLoader is exactly on point and WebFontLoader is maintained by Adobe itself (TypeKit ! )--so it's very unlikely that this CDN-link will vanish.
While I recommend WebFontLoader, you can hack together a font.onload
yourself by detecting when the width of your element changes (changed width == the font has loaded).
Adobe has created the Adobe Blank
font for the purpose of testing when a font has loaded. AdobeBlank starts out with zero width. Here's how to use AdobeBlank as font.onload
as outlined by Dr. Ken Lunde in this useful TypeKit blog post: http://blog.typekit.com/2013/03/28/introducing-adobe-blank/
Include Adobe Blank as a data URI in the CSS file.
Specify ‘font-family: SomeWebFont, “Adobe Blank” in the CSS rule for some DOM element that contains text (and would therefore have a non-zero width when rendered using a regular font). One example would be a element that is absolutely positioned offscreen.
Check the width of the DOM element. If it’s zero, SomeWebFont hasn’t loaded yet. If it’s greater than zero, it has.
Good luck with your project!
Upvotes: 2