10

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.

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
The.Anti.9
  • 43,474
  • 48
  • 123
  • 161
  • 1
    This also happens if you pass in a bad format string, such as `"12 px monospace"` with an extra space. – Noumenon Mar 25 '16 at 18:45

3 Answers3

27

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'
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
  • 4
    Great tip! I spent forever on this. Why would properties like that get reset when the size change? Seems nonsensical to me. – AdrianCooney Jun 10 '14 at 09:21
6

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.

The.Anti.9
  • 43,474
  • 48
  • 123
  • 161
  • 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. – Triynko Jul 28 '10 at 16:59
  • > 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: https://developer.mozilla.org/en/Drawing_text_using_a_canvas – richtaur May 12 '11 at 23:38
0

I had a similar issue. I had provided a div element before the canvas element and preloaded the font in it.

eg:-

.

In the CSS,

#loadFont { font-family:"arial" }

Greeshma
  • 95
  • 2
  • 10