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

余生颓废 提交于 2019-12-03 04:06:59

问题


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?


回答1:


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:

  • Dive into HTML5
  • How to display text in canvas
  • HTML5 canvas - the basics



回答2:


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.




回答3:


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/




回答4:


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



来源:https://stackoverflow.com/questions/5158222/how-do-i-style-html5-canvas-text-to-be-bold-and-or-italic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!