kelso
kelso

Reputation: 43

HTML5 Canvas, importing a local font?

I'm trying to import a font to use in the html5 canvas. I have the file on my computer, but everything I've tried so far hasn't worked. The canvas just displays a default font. I must be doing something wrong or missing a step.

I have loaded them in with CSS like this:

@font-face {
font-family: 'RifficFree-Bold';
src: local('RifficFree-Bold'), url(./fonts/RifficFree-Bold.ttf), format('truetype');
}

and then calling them in JS like so:

    function drawText(myText, ctx) {
        ctx.font = "40px RifficFree-Bold";
        ctx.fillStyle = "rgb(0, 0, 0, " + myText.fill + ")";
        ctx.fillText(myText.text, myText.x, myText.y);
    }

I know that the program is getting this far, as whenever I change 40px to another value, the size of the font changes as it should. I think I must be loading the actual font file incorrectly. Any ideas?

Upvotes: 1

Views: 4424

Answers (2)

Jave
Jave

Reputation: 31856

The actual problem in your example seems to be the comma (,) between the url and format parameters. format should be directly following the url:

src: local('RifficFree-Bold'), url(./fonts/RifficFree-Bold.ttf) format('truetype');

Upvotes: 2

Jave
Jave

Reputation: 31856

The custom font-face fonts are not loaded until they are used (you can read a question about this here). So when calling your drawText-function the font does not begin to load until ctx.fillText has been called- at which point the text has already been drawn using the default font.

You can force the browser to pre-load the font in two ways;

  1. Put a small, invisible div with some text using your font in it somewhere on the page (it can be removed after the font is loaded).

  2. If you need to load several fonts or don't want to modify your HTML, you can create a small function for loading fonts:

    function _loadFont(fontname){
        var canvas = document.createElement("canvas");
        //Setting the height and width is not really required
        canvas.width = 16;
        canvas.height = 16;
        var ctx = canvas.getContext("2d");
    
        //There is no need to attach the canvas anywhere,
        //calling fillText is enough to make the browser load the active font
    
        //If you have more than one custom font, you can just draw all of them here
        ctx.font = "4px "+fontname;
        ctx.fillText("text", 0, 8);
    }
    

    Just call the function before you need to use the font, and they should be loaded when you actually need them.

Upvotes: 2

Related Questions