processing.js, canvas, custom fonts and @font-face

So I’m fighting with what would seem to be a pretty trivial feature, but actually has very little support when it comes to web technologies. What I want to do is create a hack that allows custom fonts to be loaded into, and used inside, a processing.js canvas.

There is a CSS property called @font-face that has a lot of potential. You use @font-face is like so:

 @font-face {
 font-family: "name your font";
 src: url("url/to/your/font/file.ttf") format('truetype");

Then later in your page, you just access it by it’s name in a css font-family tag, like so : “font-family: ‘name you defined in the @font-face’;” One note about this, it wasn’t working for me using firefox and ubuntu until after I added the format tag. The strings you want to put into the format tag depend on the format of the font, so .ttf = truetype, or for .otf, you use “opentype” those are the only two I know of at the moment, but it’s pretty self explanatory.

This works, and even can then be used in a canvas elements javascript by refering to it by name inside the element, like so:

 curElement.font = "32px 'name of font'";

The big flaw in all of this, is the font is never loaded until it is used, so I would need to load an element of some sort, and say “style=”font-family: ‘name of font’;”, which would start the loading process of the font. An even bigger problem is it’s only going to be loaded if it happen to be used before the webpage is finished loading, and this is what I am stuck on.

Trying to get this to work in processing.js requires the use of the @pjs to preload, and define the fonts to be loaded. We do this for images, and it’s done like this:

 /* @pjs preload="image/url.png"; */

Multiple images can be loaded using a comma before the semi-colon.

I am thinking something like this:

 /* @pjs preloadfont="image/url.ttf"; */

When this line gets compiled, the contenet has already been loaded, and I have not yet found a way to force the load, or wait until it is finished. We do this with images, but an image is an html element that also has an onload method, that can track when it’s done loaded. This on the other hand, is a css property, which isn’t very accessible from javascript.


2 Responses to “processing.js, canvas, custom fonts and @font-face”

  1. […] to download the font; we can do this using the @font-face css rule, which I have discussed in chapter one of this font […]

  2. great blog keep up the good work .
    Al Khafji

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: