Javascript 如何将 HTML5 画布文本设置为粗体和/或斜体?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5158222/
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-08-23 15:52:45  来源:igfitidea点击:

How do I style HTML5 canvas text to be bold and/or italic?

javascripthtmlcanvastypography

提问by Ritchie

I'm printing text to a canvas in a pretty straight forward way:

我正在以一种非常直接的方式将文本打印到画布上:

var ctx = canvas.getContext('2d');
ctx.font = "10pt Courier";
ctx.fillText("Hello World", 100, 100);

But how can I change the text to bold, italic or both? Any suggestions to fix that simple example?

但是如何将文本更改为粗体、斜体或两者兼而有之?有什么建议可以解决这个简单的例子吗?

回答by Donut

You can use any of these:

您可以使用以下任何一种:

ctx.font = "italic 10pt Courier";

ctx.font = "bold 10pt Courier";

ctx.font = "italic bold 10pt Courier";

For further information, here are a couple of resources:

欲了解更多信息,这里有一些资源:

回答by tddawson

Just an additional heads up for anyone who stumbles across this: be sure to follow the order shown in the accepted answer.

对于偶然发现此问题的任何人,请额外提醒一下:请务必遵循已接受答案中显示的顺序。

I ran into some cross-browser issues when I had the wrong order. Having "10px Verdana bold" works in Chrome, but not in IE or Firefox. Switching it to "bold 10px Verdana" as indicated fixed those problems. Double-check the order if you run into similar problems.

当我有错误的订单时,我遇到了一些跨浏览器的问题。“10px Verdana bold”在 Chrome 中有效,但在 IE 或 Firefox 中无效。按照指示将其切换为“bold 10px Verdana”可以解决这些问题。如果遇到类似问题,请仔细检查订单。

回答by Jonathan Tuzman

So there's no way to just set font-weight(or font-sizeor font-family...) in one JS command? It all has to be in one complete font string?

所以没有办法只在一个 JS 命令中设置font-weightfont-sizefont-family...)?这一切都必须在一个完整的字体字符串中吗?

回答by Durgesh

Underline is not possible through any of the canvas methods or properties. But I did some work around to get it done. You can check it out @ http://scriptstock.wordpress.com/2012/06/12/html5-canvas-text-underline-workaround

无法通过任何画布方法或属性添加下划线。但我做了一些工作来完成它。您可以查看@ http://scriptstock.wordpress.com/2012/06/12/html5-canvas-text-underline-workaround

You can find the implementation here http://jsfiddle.net/durgesh0000/KabZG/

你可以在这里找到实现http://jsfiddle.net/durgesh0000/KabZG/