开发者

HTML 5 canvas font being ignored

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";
   开发者_JAVA百科 ctx.font = "12px monospace";
    ctx.textBaseline = "top";
}

It doesn't work in either Firefox or Chrome.


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'


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.


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" }

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜