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

JavascriptHtmlCanvasTypography

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRitchieView Question on Stackoverflow
Solution 1 - JavascriptDonutView Answer on Stackoverflow
Solution 2 - JavascripttddawsonView Answer on Stackoverflow
Solution 3 - JavascriptDurgeshView Answer on Stackoverflow
Solution 4 - JavascriptKyleMitView Answer on Stackoverflow