Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 378
jdee Avatar asked Apr 09 '10 13:04

jdee


People also ask

How do I add custom fonts to canvas?

canvas = document. querySelector('canvas'); var myFont = new FontFace('myFont', 'url(assets/fonts/myFont/myFont. otf)'); Now we create our font object using the javascript class FontFace which receives the font family and the source.

Can I use different fonts in canvas?

While Canvas offers seven different font sizes, there is always the chance you need one more. The easiest way to do this is to: highlight the line or block of text you wish to change. select a font size other than the default of 12pt.

How do you customize a font in HTML?

To change font size in HTML, use the CSS font-size property. Set it to the value you want and place it inside a style attribute. Then add this style attribute to an HTML element, like a paragraph, heading, button, or span tag.


1 Answers

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); }; 
like image 114
miketaylr Avatar answered Oct 13 '22 16:10

miketaylr