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

HtmlCanvasFontsCufontypeface.js

Html Problem Overview


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>

Anyone got any ideas?

Html Solutions


Solution 1 - Html

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

Solution 2 - Html

I have just answered this question here: https://stackoverflow.com/questions/15540591/preload-font-html5-js-kinetic-js/15973926#15973926

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjdeeView Question on Stackoverflow
Solution 1 - HtmlmiketaylrView Answer on Stackoverflow
Solution 2 - HtmlandyrandyView Answer on Stackoverflow