Skip to content
Advertisement

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?

Advertisement

Answer

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:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement