仅在加载Google Web字体后才能绘制到画布 [英] Draw to canvas only after Google Web Font is loaded

查看:48
本文介绍了仅在加载Google Web字体后才能绘制到画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在画布上使用 .fillText(),我想在其文本中使用Google Web字体(在我的情况下为Oswald).

I am using .fillText() on a canvas, the text of which I want to be in a Google Web Font (Oswald, in my case).

页面加载时,在加载字体之前将文本绘制到画布上,但是很显然,一旦字体加载,画布上的文本就不会更新,因为它已经作为位图绘制了.

When the page loads, the text is drawn to canvas before the font has loaded, but obviously once the font loads the text on the canvas doesn't update, because it has already been drawn as a bitmap.

如何将文本绘制延迟到Web字体加载之后?我仍然想立即在 $(document).ready().

How can I delay this text drawing until after the Web Font has loaded? A rectangle is also drawn to the canvas which I would still like to draw immediately on $(document).ready().

我应该说,我想延迟 .fillText()而不是覆盖默认字体,因为它是一种面向设计的应用程序,并且FOUT对美感产生了负面影响./p>

I should say that I would like to delay the .fillText() instead of overwriting the default font, since it is a design-oriented application, and the FOUT reflects negatively on the aesthetics.

推荐答案

下面是一个如何使用TypeKit的WebFontLoader允许字体在使用之前加载的示例:

Here's an example of how to use TypeKit's WebFontLoader to allow fonts time to load before using them:

// load google font == Monoton
WebFontConfig = {
  google:{ families: ['Monoton'] },
  active: function(){start();},
};
(function(){
  var wf = document.createElement("script");
  wf.src = 'https://ajax.googleapis.com/ajax/libs/webfont/1.5.10/webfont.js';
  wf.async = 'true';
  document.head.appendChild(wf);
})();


var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;


function start(){
  ctx.font = '50px Monoton';
  ctx.textBaseline = 'top';
  ctx.fillText('No', 20, 10);
}

body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}

<canvas id="canvas" width=300 height=300></canvas>

这篇关于仅在加载Google Web字体后才能绘制到画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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