ChatGPT解决这个技术问题 Extra ChatGPT

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

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?


D
Donut

From the MDN documentation on CanvasRenderingContext2D.font:

The CanvasRenderingContext2D.font property of the Canvas 2D API specifies the current text style to use when drawing text. This string uses the same syntax as the CSS font specifier.

So, that means any of the following will work:

ctx.font = "italic 10pt Courier";

ctx.font = "bold 10pt Courier";

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

Here are a couple of additional resources for more information:

Dive into HTML5

HTML5 canvas - the basics


Arg beat me to it, +1 Great site for more info, diveintohtml5.org/canvas.html#divingin
@Loktar Thanks for the link, included it in answer.
You can also specify the font weight: ctx.font = "400 10pt Courier"
Font weight via ctx.font = "400 10pt Open Sans" didn't work for me in Chrome using Calibri or Open Sans in latest browser versions
t
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.


Chrome seems to have changed so that it is in-line with Firefox. See this pen: codepen.io/anon/pen/BXNZxO
D
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

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


K
KyleMit

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:

// get canvas / context var can = document.getElementById('my-canvas'); var ctx = can.getContext('2d') // draw first text var text = '99%'; ctx.font = 'bold 12pt Courier'; ctx.fillText(text, 50, 50); // measure text var textWidth = ctx.measureText(text).width; // draw second text ctx.font = 'normal 12pt Courier'; ctx.fillText(' invisible', 50 + textWidth, 50);

Further Reading

MDN > Canvas > Drawing text

formatting individual words with italics