最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Draw to canvas only after Google Web Font is loaded - Stack Overflow

programmeradmin2浏览0评论

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.

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

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.

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.

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

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.

Share Improve this question asked Mar 28, 2015 at 9:56 hotstuff69hotstuff69 1731 silver badge4 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 9

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

发布评论

评论列表(0)

  1. 暂无评论