延迟画布的javascript执行,直到加载了字体为止 [英] delay execution of javascript for canvas until fonts have been loaded

查看:69
本文介绍了延迟画布的javascript执行,直到加载了字体为止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在画布中制作一些东西,该东西使用来自Web服务的字体,发生的情况是,当第一次加载画布时,我从google字体加载的字体尚未到来,因此最简单的是瞬间,画布中只有纯字体,然后切换到我下载的字体.

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.

这是一个很小的细节,但很烦人.我想知道是否有任何方法可以预加载字体,即在确定已经拥有字体之后才执行与画布相关的javascript代码.

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.

字体放置在html的标题中:

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'>

和js链接位于文件底部,就在主体关闭之前.

and the js links at the bottom of the file, just before the closing of the body.

推荐答案

使用Google的WebFontLoader脚本

https://github.com/typekit/webfontloader

WebFontLoader的 fontactive 回调等效于img元素的 onload .

WebFontLoader's fontactive callback is the equivalent of the img element's onload.

WebFontLoader完全正确,并且WebFontLoader由Adobe自己维护(TypeKit!)-因此,该CDN链接消失的可能性很小.

WebFontLoader is exactly on point and WebFontLoader is maintained by Adobe itself (TypeKit ! )--so it's very unlikely that this CDN-link will vanish.

虽然我建议使用WebFontLoader,但您可以通过检测元素的宽度何时更改(更改的宽度==字体已加载)来自己破解 font.onload .

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

Adob​​e已创建 Adob​​e Blank 字体,用于测试加载字体时的目的.AdobeBlank以零宽度开始.Ken Lunde博士在此有用的TypeKit博客文章中概述的方法如下,将AdobeBlank用作 font.onload :

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. 将Adobe Blank作为数据URI包含在CSS文件中.

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

在CSS规则中为某些包含文本的DOM元素(在使用常规字体呈现时宽度为非零)中指定'font-family:SomeWebFont,"Adob​​e Blank".一个示例是绝对位于屏幕外的元素.

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.

检查DOM元素的宽度.如果为零,则表示尚未加载SomeWebFont.如果大于零,则为零.

Check the width of the DOM element. If it’s zero, SomeWebFont hasn’t loaded yet. If it’s greater than zero, it has.

祝您的项目好运!

这篇关于延迟画布的javascript执行,直到加载了字体为止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆