简体   繁体   中英

delay execution of javascript for canvas until fonts have been loaded

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, ie 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.

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/

  1. Include Adobe Blank as a data URI in the CSS file.

  2. 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.

  3. 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM