如何将 HTML5 画布文本设置为粗体和/或斜体?
我正在以一种非常直接的方式将文本打印到画布上:
var ctx = canvas.getContext('2d');
ctx.font = "10pt Courier";
ctx.fillText("Hello World", 100, 100);
但是如何将文本更改为粗体、斜体或两者兼而有之?有什么建议来修复这个简单的例子吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自 MDN 文档
CanvasRenderingContext2D.font
:因此,这意味着以下任何一种方法都可以:
以下是一些额外资源,可提供更多信息:
From the MDN documentation on
CanvasRenderingContext2D.font
:So, that means any of the following will work:
Here are a couple of additional resources for more information:
对于任何偶然发现此问题的人来说,请务必注意:请务必遵循已接受答案中显示的顺序。
当我的顺序错误时,我遇到了一些跨浏览器问题。 “10px Verdana 粗体”在 Chrome 中有效,但在 IE 或 Firefox 中无效。将其切换为“bold 10px Verdana”,如图所示修复了这些问题。如果遇到类似问题,请仔细检查订单。
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.
如果您需要允许格式变化,您可以设置字体样式、绘制文本、使用
measureText
,设置一个新的样式,然后像这样绘制下一个块:进一步阅读
If you need to allow for variations in formatting, you can set a font style, draw text, measure it using
measureText
, set a new style, and then draw the next block like this:Further Reading
无法通过任何画布方法或属性添加下划线。但我做了一些工作来完成它。您可以查看@ http://scriptstock.wordpress .com/2012/06/12/html5-canvas-text-underline-workaround
您可以在此处找到实现 http://jsfiddle.net/durgesh0000/KabZG/
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
You can find the implementation here http://jsfiddle.net/durgesh0000/KabZG/