HTML 5 canvas font being ignored

12,479

Solution 1

As it turns out, the ctx.font change needs to be used in the same function that is doing the fillText()

This makes it work like a charm.

EDIT

As richtaur mentioned in his comment, this answer is wrong. Your context needs to be saved and restored using ctx.save() and ctx.restore() as it currently gets reset when you call canvas.getContext('2d') again.

Solution 2

That this can also happen if you reset the size of the canvas. At least, I saw this in Chrome 23 today.

context.font = 'bold 20px arial';
canvas.width = 100;
canvas.height = 100;
console.log(context.font); // gives '10px sans-serif'
Share:
12,479
Per Knytt
Author by

Per Knytt

I am a programmer always looking to learn more.

Updated on June 08, 2022

Comments

  • Per Knytt
    Per Knytt almost 2 years

    I'm trying to write some text to a canvas element, but it seems that the font options I put in are being completely ignored. No matter what I change them to, it all comes out the same, which I believe to be the default 10px sans-serif. Heres what I have (this function runs on load)

    function start()
    {
        canvas = document.getElementById('c');
        ctx = canvas.getContext('2d');
        ctx.fillStyle = "white";
        ctx.font = "12px monospace";
        ctx.textBaseline = "top";
    }
    

    It doesn't work in either Firefox or Chrome.

    • Noumenon
      Noumenon about 8 years
      This also happens if you pass in a bad format string, such as "12 px monospace" with an extra space.
  • Triynko
    Triynko almost 14 years
    I suspect that each time you re-acquire the graphics context with canvas.getContext('2d') you get a new context that's reset to the default font. This makes sense, because you're performing drawing operations, and probably going to render all kinds of text in all different fonts, and cycle through them as you render each frame... so (re)setting the font for each new context makes sense.
  • richtaur
    richtaur almost 13 years
    > As it turns out, the ctx.font change needs to be used in the same function that is doing the fillText() <-- That's not how it works. Settings are global to that context so it's probably getting overridden in your other function. You'd want to do like ctx.save() then ctx.restore() to save the state of your context. See: developer.mozilla.org/en/Drawing_text_using_a_canvas
  • AdrianCooney
    AdrianCooney almost 10 years
    Great tip! I spent forever on this. Why would properties like that get reset when the size change? Seems nonsensical to me.