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

4

107

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?

Cita answered 1/3, 2011 at 17:42 Comment(0)
B
194

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:

Bewail answered 1/3, 2011 at 17:44 Comment(6)
Arg beat me to it, +1 Great site for more info, diveintohtml5.org/canvas.html#divinginCritic
@Critic Thanks for the link, included it in answer.Bewail
regarding underline: #4627633Wallet
You can also specify the font weight: ctx.font = "400 10pt Courier"Gerhard
Font weight via ctx.font = "400 10pt Open Sans" didn't work for me in Chrome using Calibri or Open Sans in latest browser versionsEquiponderance
First two links are brokenBiracial
T
16

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.

Tsaritsyn answered 7/7, 2014 at 20:52 Comment(1)
Chrome seems to have changed so that it is in-line with Firefox. See this pen: codepen.io/anon/pen/BXNZxOLoriannlorianna
D
3

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);
<canvas id="my-canvas" width="250" height="150"></canvas>

Further Reading

Desmond answered 19/11, 2020 at 19:57 Comment(0)
C
2

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/

Cimbura answered 13/6, 2012 at 18:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.