【问题标题】:Using font-face fonts with canvas fillText将 font-face 字体与画布 fillText 一起使用
【发布时间】:2011-09-11 23:19:38
【问题描述】:

编辑:嗯,似乎字体一旦被 DOM 上的元素使用就被加载了,所以我只是使用了一个隐藏的 Div 和使用 font-face 字体的文本,它正在工作现在... :)

我正在使用此代码通过一些更新来更新网站图标,但我想使用自定义像素字体写入数字。

这是我的 Javascript 代码

            var canvas = document.createElement('canvas'),
            ctx,
            img = document.createElement('img'),
            link = document.getElementById('favicon').cloneNode(true),
            updates = data;

        if (canvas.getContext) {
          canvas.height = canvas.width = 16; // set the size
          ctx = canvas.getContext('2d');
          img.onload = function () { // once the image has loaded
            ctx.drawImage(this, 0, 0);
            ctx.font = 'normal 12px Visitor';
            ctx.fillStyle = '#213B55';
            ctx.textBaseline="middle";
            ctx.textAlign="center";
            ctx.fillText(updates, 10, 10);
            link.href = canvas.toDataURL('image/png');
            document.body.appendChild(link);
          };
          img.src = 'favicon_new.png';
        }

这是在我的 CSS 中

@font-face {
font-family: 'Visitor';
font -style: normal;
font-weight: normal;
src: url('fonts/visitor.woff') format('woff');

如果我改变这一行:

  ctx.font = 'normal 12px Visitor';

使用 'normal 12px Arial' 可以正常工作。如果我使用自定义的“访客”字体,它只会更改图标,但我看不到数字。

知道可能是什么问题吗?

【问题讨论】:

  • 查看我使用 元素加载字体的解决方案:stackoverflow.com/questions/8198967/…
  • 您也可以使用 CSS 中的数据 url 加载字体,这对我有用。
  • 不要害怕发布您的“编辑”作为答案。
  • 是的,请将您的编辑作为答案发布并接受它,这样它就不会再出现在未回答的队列中,并且有此问题的人更容易找到答案
  • 当心,隐藏的 div 技巧似乎并不总是有效。很抱歉,我现在不知道在哪个配置中,但我看到它失败了 - 如果它适用于您的目标浏览器,这不是问题 -

标签: html canvas font-face


【解决方案1】:

Arial 是一种网络安全字体,这意味着无论您使用什么计算机或移动设备(又名备用),它都会显示。

这是来自 Google Fonts 的一些带有 Pacifico 的示例代码(它不是网络安全字体)。

<link href="http://fonts.googleapis.com/css?family=Pacifico" rel="stylesheet" type="text/css">
<script>
 window.onload=function() {
  var canvas = document.getElementById("canvas");
  var context = canvas.getContext("2d");
  context.fillStyle = "blue";
  context.font = "16pt Pacifico";
  context.fillText("Cursive font", 50, 50);
 }
</script>
<canvas id="canvas" width="200" height="200"></canvas>

其他字体应该可以的。

确保您的 @font-face 具有 font-style: normal;font-weight: 400;

【讨论】:

    猜你喜欢
    • 2019-05-15
    • 2011-08-01
    • 2014-01-22
    • 2014-09-04
    • 2012-02-07
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多