Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 873
Ritchie Avatar asked Mar 01 '11 17:03

Ritchie


People also ask

How do I make text bold and italic in HTML?

HTML Formatting Elements<b> - Bold text. <strong> - Important text. <i> - Italic text.

How do you italicize on canvas?

To bold or italicize your text in Canva, start by clicking on your desired text to select it. If your chosen font can be bolded or italicized, you'll see options for them appear in black in your top toolbar. Choose either the B button for bolding or the I button for italicizing.

How do you write italics in html5?

To make text italic in HTML, use the <i>… </i> tag or <em>… </em> tag. Both the tags have the same functioning, but <em> tag is a phrase tag, which renders as emphasized text.

How do I make text bold and italicize?

To make text bold, select and highlight the text first. Then hold down Ctrl (the control key) on the keyboard and press B on the keyboard. To make text italic, select and highlight the text first. Then hold down Ctrl (the control key) on the keyboard and then press the I on the keyboard.


2 Answers

You can use any of these:

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

For further information, here are a couple of resources:

  • Dive into HTML5
  • How to display text in canvas
  • HTML5 canvas - the basics
like image 133
Donut Avatar answered Sep 26 '22 04:09

Donut


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.

like image 30
tddawson Avatar answered Sep 25 '22 04:09

tddawson