2011-06-09 143 views
4

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

我使用此代码来更新favicon与一些更新,但我想写一个自定义像素字体的数字。

这是我的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'; 

随着'正常12px的宋体'作品精细。如果我使用自定义的“访客”字体,它只是改变图标,但我看不到数字。

任何想法可能是什么问题?

+0

查看我的使用元素加载字体的解决方案:http://stackoverflow.com/questions/8198967/html5-canvas-filltext-and-font-face/8222880#8222880 – 2011-11-22 07:48:25

+0

您也可以加载字体在你的CSS中使用数据网址,这对我很有用。 – Blaise 2012-11-25 21:22:43

+2

不要害怕发布你的'编辑'作为答案。 – xdhmoore 2013-09-03 20:53:00

回答

1

宋体是网络安全的字体,这意味着,这将是不管你有什么计算机或移动设备(又名后备)所示。

以下是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-facefont-style:normal;font-weight:400;