javascript HTML 5 画布字体被忽略

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3349947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 00:55:11  来源:igfitidea点击:

HTML 5 canvas font being ignored

javascripthtmlcanvasfonts

提问by The.Anti.9

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)

我正在尝试将一些文本写入画布元素,但似乎我输入的字体选项被完全忽略了。不管我把它们改成什么,结果都是一样的,我相信这是默认的 10px sans-serif。这是我所拥有的(此功能在加载时运行)

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.

它不适用于 Firefox 或 Chrome。

采纳答案by The.Anti.9

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

事实证明,ctx.font更改需要在执行此操作的同一函数中使用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.

正如 Richtaur 在他的评论中提到的,这个答案是错误的。您的上下文需要使用ctx.save()和进行保存和恢复,ctx.restore()因为当您再次调用 canvas.getContext('2d') 时,它当前会被重置。

回答by Drew Noakes

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

如果您重置画布的大小,也会发生这种情况。至少,我今天在 Chrome 23 中看到了这一点。

context.font = 'bold 20px arial';
canvas.width = 100;
canvas.height = 100;
console.log(context.font); // gives '10px sans-serif'