Html 如何在 HTML5 Canvas 元素中使用自定义字体?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2608022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use custom fonts in an HTML5 Canvas element?
提问by jdee
I've looked at things like Cufon and typeface.js but they seem to be SIFR alternatives and don't allow you to set freeform coordinates and draw custom type onto a <canvas>
我看过 Cufon 和 typeface.js 之类的东西,但它们似乎是 SIFR 的替代品,并且不允许您设置自由坐标并将自定义类型绘制到 <canvas>
Anyone got any ideas?
有人有任何想法吗?
回答by miketaylr
I've thrown together a simple demo on jsfiddle here showing how to do this with @font-face: http://jsfiddle.net/zMKge/
我在这里拼凑了一个关于 jsfiddle 的简单演示,展示了如何使用 @font-face 做到这一点:http: //jsfiddle.net/zMKge/
Opera also has a simple tutorialon using <canvas>
, including the text API.
Opera 还有一个简单的使用教程<canvas>
,包括文本 API。
CSS:
CSS:
@font-face {
font-family: 'KulminoituvaRegular';
src: url('http://www.miketaylr.com/f/kulminoituva.ttf');
}
Javascript:
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);
};
回答by luschn
I have just answered this question here: Preload font HTML5, JS, Kinetic.js?
我刚刚在这里回答了这个问题: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.
无论您是否使用 KineticJS,都没有关系,没有 KineticJS 的唯一区别是您可能会直接使用 HTML 创建 Canvas 元素,而不是使用 div 层作为容器。毕竟 KineticJS 只是在该容器中创建了一个普通的 Canvas 元素。