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

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

有人知道吗?

94540 次浏览

I've thrown together a simple demo on jsfiddle here showing how to do this with @font-face: http://jsfiddle.net/zMKge/

Opera also has a simple tutorial on using <canvas>, including the text 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);
};

I have just answered this question here: Preload font HTML5, JS, Kinetic.js?

The essential part:

@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;
}

It should not matter if you are using KineticJS or not, the only difference without KineticJS is that you would possibly create the Canvas element directly with HTML instead of using a div layer as container. After all KineticJS just creates a normal Canvas element in that container.

an answer from 3 years into the future lol

you can user javascript's new FontFace(family, font, descriptor)

https://developer.mozilla.org/en-US/docs/Web/API/FontFace/FontFace

where family is the name of the font, font is a url or ttf binary data, and descriptor is css elements.

then use ctx.fillText() to create the text