我一直在为此挣扎几天无济于事,但似乎这应该是一件简单的事情。
第一次绘制画布时,我无法正确显示 Google 字体。字体的后续显示正常。这当然似乎与加载字体的时间有关。
我已经尝试了使用@font-face 将文本绘制到 <canvas> 中列出的大多数建议修复程序在第一次不起作用但没有成功。
这是我的 jsfiddle 合并了上述链接中的大部分修复:http: //jsfiddle.net/HatHead/GcxQ9/23/
加载 jsfiddle 时,您会看到画布标题和文本是默认字体。当您按下运行按钮时,字体将更新为 js 代码指定的字体。
以下是来自上述 jsfiddle 的代码:
HTML:
<!-- you need to empty your browser cache and do a hard reload EVERYTIME to test this otherwise it will appear to working when, in fact, it isn't -->
<h1>Title Font</h1>
<p>Paragraph font...</p>
<canvas id="myCanvas" width="740" height="400"></canvas>
CSS:
@import url(http://fonts.googleapis.com/css?family=Architects+Daughter);
@import url(http://fonts.googleapis.com/css?family=Rock+Salt);
canvas {
font-family:'Rock Salt', 'Architects Daughter'
}
.wf-loading p {
font-family: serif
}
.wf-inactive p {
font-family: serif
}
.wf-active p {
font-family:'Architects Daughter', serif;
font-size: 24px;
font-weight: bold;
}
.wf-loading h1 {
font-family: serif;
font-weight: 400;
font-size: 42px
}
.wf-inactive h1 {
font-family: serif;
font-weight: 400;
font-size: 42px
}
.wf-active h1 {
font-family:'Rock Salt', serif;
font-weight: 400;
font-size: 42px;
}
JS:
// do the Google Font Loader stuff....
WebFontConfig = {
google: {
families: ['Architects Daughter', 'Rock Salt']
}
};
(function () {
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
'://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})();
//play with the milliseconds delay to find the threshold - don't forget to empty your browser cache and do a hard reload!
setTimeout(WriteCanvasText, 0);
function WriteCanvasText() {
// write some text to the canvas
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.font = "normal" + " " + "normal" + " " + "bold" + " " + "42px" + " " + "Rock Salt";
context.fillStyle = "#d50";
context.fillText("Canvas Title", 5, 100);
context.font = "normal" + " " + "normal" + " " + "bold" + " " + "24px" + " " + "Architects Daughter";
context.fillText("Here is some text on the canvas...", 5, 180);
}
它使用延迟工作,但这是一个糟糕的解决方案。
有什么想法可以解决这个问题吗?以前有人打过吗?我不愿意放弃并在第一次加载时放入图像代替文本。
非常感谢stackoverflow'ers!