Categories
JavaScript Answers

How to Style HTML5 Canvas Text to be Bold or Italic with JavaScript?

Spread the love

Sometimes, we want to style HTML5 canvas text to be bold or italic with JavaScript.

In this article, we’ll look at how to style HTML5 canvas text to be bold or italic with JavaScript.

Style HTML5 Canvas Text to be Bold or Italic with JavaScript

To style HTML5 canvas text to be bold or italic, we can set the font property of the 2d canvas context with the style of the text.

For instance, we can write the following HTML:

<canvas style='width: 200px; height: 200px'></canvas>

to add the canvas element.

Then we can write the following JavaScript:

const canvas = document.querySelector("canvas");  
const ctx = canvas.getContext("2d");  
ctx.font = "italic bold 20pt Courier";  
ctx.fillText("Hello World", 10, 50);

to get the canvas with document.querySelector .

Then we call getContext with '2d' to get the 2d canvas context.

Next, we set the font property of the returned context object with a string with the text styles.

italic makes it italic. bold makes it bold. 20pt is the text size. Courier is the font family.

Finally, we call fillText with the text that we want to display and the x and y coordinates of the top left corner of the text.

Now we should see ‘Hello World’ displayed with Courier font, bold, and italic as a result.

Conclusion

To style HTML5 canvas text to be bold or italic, we can set the font property of the 2d canvas context with the style of the text.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *