HTML5 Canvas filltext和font-face [英] HTML5 Canvas filltext and font-face

查看:227
本文介绍了HTML5 Canvas filltext和font-face的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过来看stackoverflow和谷歌的方法来解决这个问题im has但havent有很多运气的解决方案。

Been looking around stackoverflow and google for ways to solve this issue im having but havent had much luck with a solution.

发生的是我的font-face字体在正确的时间未加载。我所做的是我有一个html5画布和javascript,我在其中绘制一些简单的圆与填充文本。现在圆圈正在绘制,但文本本身是错误的字体。

What is happening is my font-face font is not loading at the right time. What I have going on is I have a html5 canvas and javascript where I am drawing some simple circles with fill text inside them. Now the circles are getting drawn but the text itself is the wrong font.

我假设原因是因为字体是最后加载,它只是选择默认字体。

I'm assuming the reason being is because the font is being loaded last and it just picks the default font.

现在我的问题是...有一种方法,我可以延迟画布对象,直到加载字体?这种方式的字体将准备使用,它会分配正确的字体到画布对象。

Now my question is... is there a way I can delay the canvas objects being drawn until the font is loaded? This way the font will be ready to use and it will assign the right fonts to the canvas objects.

我应该指出,我有一个index.php文件,包括

I should point out that I have a index.php file that includes my other php file where the javascript and canvas is actually being drawn.

推荐答案

使用这个技巧,并将 onerror 事件绑定到 Image 元素。

Use this trick and bind an onerror event to an Image element.

在此演示: http://jsfiddle.net/g6LyK/ - 适用于最新的Chrome。

Demo here: http://jsfiddle.net/g6LyK/ — works on the latest Chrome.

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'http://fonts.googleapis.com/css?family=Vast+Shadow';
document.getElementsByTagName('head')[0].appendChild(link);

// Trick from http://stackoverflow.com/questions/2635814/
var image = new Image;
image.src = link.href;
image.onerror = function() {
    ctx.font = '50px "Vast Shadow"';
    ctx.textBaseline = 'top';
    ctx.fillText('Hello!', 20, 10);
};

这篇关于HTML5 Canvas filltext和font-face的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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