How can I use custom fonts in an HTML5 Canvas element?

I looked at things like Cufon and typeface.js, but they seem to be alternatives to SIFR and do not allow you to set free-form coordinates and draw your own type on <canvas>

Does anyone have any idea?

+59
html5 fonts canvas cufon
Apr 09 '10 at
source share
2 answers

I put together a simple demo on jsfiddle, which shows how to do this with @ font-face: http://jsfiddle.net/zMKge/

Opera also has a simple tutorial on using <canvas> , including a text API, but I'm not cool enough to have two hyperlinks. :)

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); }; 
+77
Apr 09 '10 at 18:26
source share

I just answered this question here: HTML5 preview font, 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 doesn't matter if you use KineticJS or not, the only difference without KineticJS is that you could create a Canvas element directly from HTML instead of using a div layer as a container. In the end, KineticJS creates a regular Canvas container in that container.

+4
Apr 12 '13 at 14:35
source share



All Articles