简体   繁体   English

如何在画布元素上呈现图标字体字形?

[英]How do I render icon font glyphs on a canvas element?

I'm using a font from http://icomoon.io/ on a project and need to draw this to a canvas element with fillText . 我在项目上使用了http://icomoon.io/中的字体,并且需要使用fillText将其绘制到画布元素上。

var charCode = 0xe00e;
context.font = "20px icomoon";
context.fillText(String.fromCharCode(charCode));

The font is being included in CSS (and is also installed locally) but instead of the picture of a house I want to see, it renders a '2'. 该字体已包含在CSS中(并且也已在本地安装),但它呈现的是“ 2”,而不是我想要看到的房屋图片。

What can I do to debug this problem? 我该怎么做才能调试此问题?

To be a bit clearer: I'm trying to render specific glyphs by character code rather than straightforward strings. 更清楚一点:我正在尝试通过字符代码而不是简单的字符串来呈现特定的字形。

Try this 试试这个

@font-face {
    font-family: 'KulminoituvaRegular';
    src: url('http://www.miketaylr.com/f/kulminoituva.ttf');
}
var ctx = document.getElementById('c').getContext('2d');
ctx.font = '36px KulminoituvaRegular';
ctx.textBaseline = 'top';
ctx.fillStyle = 'black';
ctx.fillText  ('Kulminoituva Regular', 10, 10);

One fix is to just use the SVG font that ico moon provides. 一种解决方法是仅使用ico moon提供的SVG字体。 That's the line that looks like this: 那行看起来像这样:

url('../fonts/icomoon.svg#icomoon') format('svg')

I believe the canvas needs that SVG data to render the icon, if you are using one of the other various font formats (eot, woff, ttf) the canvas doesn't know how to interpret the unicode conversion. 我相信画布需要SVG数据来呈现图标,如果您使用其他各种字体格式(eot,woff,ttf)之一,则画布不知道如何解释unicode转换。

The good news is that svg is supported in all the same browsers as the html canvas. 好消息是,与html canvas相同的所有浏览器都支持svg。

Update: To clarify, your font embed should have the SVG line after all the other src lines like so: 更新:为澄清起见,嵌入的字体应在所有其他src行之后加上SVG行,如下所示:

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

} }

Try inserting \\u before the desired character code for eg if character code is '0xe00e', use '\\u0xe00e' 尝试在所需的字符代码之前插入\\ u,例如,如果字符代码为'0xe00e',则使用'\\ u0xe00e'

 context.font = '20px icomoon';
 context.fillText('\u0xe00e', 20, 20);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM