使用@font-face 将文本绘制到 <canvas> 第一次不起作用

新手上路,请多包涵

当我使用通过@font-face 加载的字体在画布中绘制文本时,文本无法正确显示。它根本不显示(在 Chrome 13 和 Firefox 5 中),或者字体错误(Opera 11)。这种类型的意外行为只发生在第一次使用该字体绘制时。之后一切正常。

这是标准行为还是什么?

谢谢你。

PS:以下是测试用例的源码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>@font-face and &lt;canvas&gt;</title>
        <style id="css">
@font-face {
    font-family: 'Press Start 2P';
    src: url('fonts/PressStart2P.ttf');
}
        </style>
        <style>
canvas, pre {
    border: 1px solid black;
    padding: 0 1em;
}
        </style>
    </head>
    <body>
        <h1>@font-face and &lt;canvas&gt;</h1>
        <p>
            Description: click the button several times, and you will see the problem.
            The first line won't show at all, or with a wrong typeface even if it does.
            <strong>If you have visited this page before, you may have to refresh (or reload) it.</strong>
        </p>
        <p>
            <button id="draw">#draw</button>
        </p>
        <p>
            <canvas width="250" height="250">
                Your browser does not support the CANVAS element.
                Try the latest Firefox, Google Chrome, Safari or Opera.
            </canvas>
        </p>
        <h2>@font-face</h2>
        <pre id="view-css"></pre>
        <h2>Script</h2>
        <pre id="view-script"></pre>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        <script id="script">
var x = 30,
    y = 10;

$('#draw').click(function () {
    var canvas = $('canvas')[0],
        ctx = canvas.getContext('2d');
    ctx.font = '12px "Press Start 2P"';
    ctx.fillStyle = '#000';
    ctx.fillText('Hello, world!', x, y += 20);
    ctx.fillRect(x - 20, y - 10, 10, 10);
});
        </script>
        <script>
$('#view-css').text($('#css').text());
$('#view-script').text($('#script').text());
        </script>
    </body>
</html>

原文由 lemonedo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 325
1 个回答

当您调用 fillText 方法时,必须在画布上绘图并立即返回。但是,浏览器还没有从网络加载字体,这是一个后台任务。所以它必须回退到它 确实 可用的字体。

如果您想确保字体可用,请在页面上预加载一些其他元素,例如:

 <div style="font-family: PressStart;">.</div>

原文由 bobince 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题