2011-06-09 24 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;