Michael Forrest
Michael Forrest

Reputation: 3511

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.

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'.

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.

Upvotes: 4

Views: 4208

Answers (3)

Gaurav
Gaurav

Reputation: 1

Try inserting \u before the desired character code for e.g. if character code is '0xe00e', use '\u0xe00e'

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

Upvotes: 0

unpollo
unpollo

Reputation: 804

One fix is to just use the SVG font that ico moon provides. 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.

The good news is that svg is supported in all the same browsers as the html canvas.

Update: To clarify, your font embed should have the SVG line after all the other src lines like so:

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

}

Upvotes: 1

Cerbrus
Cerbrus

Reputation: 72957

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);

Upvotes: 4

Related Questions