如何在HTML5 Canvas元素中使用自定义字体?

问题描述 投票:67回答:2

我看过像Cufon和typeface.js这样的东西,但它们似乎是SIFR替代品,不允许你设置自由形式坐标并将自定义类型绘制到<canvas>

有人有任何想法吗?

html5 canvas fonts cufon typeface.js
2个回答
91
投票

我在jsfiddle上汇总了一个简单的演示,在这里展示如何使用@ font-face执行此操作:http://jsfiddle.net/zMKge/

Opera也有使用simple tutorial<canvas>,包括文本API。

CSS:

@font-face {
    font-family: 'KulminoituvaRegular';
    src: url('http://www.miketaylr.com/f/kulminoituva.ttf');
}

使用Javascript:

var ctx = document.getElementById('c').getContext('2d');
var kitty = new Image();
kitty.src = 'http://i954.photobucket.com/albums/ae30/rte148/891blog_keyboard_cat.gif';
kitty.onload = function(){
  ctx.drawImage(this, 0,0,this.width, this.height);
  ctx.font         = '68px KulminoituvaRegular';
  ctx.fillStyle = 'orangered';
  ctx.textBaseline = 'top';
  ctx.fillText  ('Keyboard Cat', 0, 270);
};

5
投票

我刚才在这里回答了这个问题:Preload font HTML5, JS, Kinetic.js?

至关重要的部分:

@font-face {
    font-family: 'myfont';
    src: url('myfont.eot');
    src: url('myfont.eot?#iefix') format('embedded-opentype'),
         url('myfont.woff') format('woff'),
         url('myfont.ttf') format('truetype'),
         url('myfont.svg#myfont') format('svg');
    font-weight: normal;
    font-style: normal;
}

无论你是否使用KineticJS都没关系,没有KineticJS的唯一区别是你可能直接用HTML创建Canvas元素而不是使用div层作为容器。毕竟KineticJS只是在该容器中创建了一个普通的Canvas元素。

© www.soinside.com 2019 - 2024. All rights reserved.