How do I style HTML5 canvas text to be bold and/or italic?
Solution 1
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:
Solution 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.
Solution 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/
Solution 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?
Ritchie
Updated on July 08, 2022Comments
-
Ritchie almost 2 years
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?
-
Loktar over 13 yearsArg beat me to it, +1 Great site for more info, diveintohtml5.org/canvas.html#divingin
-
Donut over 13 years@Loktar Thanks for the link, included it in answer.
-
jedierikb over 11 yearsregarding underline: stackoverflow.com/questions/4627133/…
-
Ivan P about 11 yearsYou can also specify the font weight:
ctx.font = "400 10pt Courier"
-
ecc521 almost 5 yearsChrome seems to have changed so that it is in-line with Firefox. See this pen: codepen.io/anon/pen/BXNZxO
-
sean2078 over 4 yearsFont weight via
ctx.font = "400 10pt Open Sans"
didn't work for me in Chrome using Calibri or Open Sans in latest browser versions -
Yong over 2 yearsFirst two links are broken