Font Size:

 

The font property in canvas allows you to set the font size along with other font properties like font family. Here's an example of how to customize font size:


const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');


// Set font size and family
ctx.font = '30px Arial';
ctx.fillText('Hello, World!', 50, 50); // Render text at coordinates (50, 50)
 



In this example:

 

We use ctx.font = '30px Arial'; to set the font size to 30 pixels and the font family to Arial.
Then, we use ctx.fillText to render the text "Hello, World!" on the canvas.
Font Family:


You can specify the font family using the font property. Here's an example:


const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// Set font size and family
ctx.font = 'italic bold 30px Times New Roman';
ctx.fillText('Hello, World!', 50, 50); // Render text at coordinates (50, 50)



In this example:

 
  • We use ctx.font = 'italic bold 30px Times New Roman'; to set the font style to italic, font weight to bold, font size to 30 pixels, and font family to Times New Roman.
  • Then, we use ctx.fillText to render the text "Hello, World!" using the specified font style.


Font Weight:

 

The font weight property determines how thick or thin characters in text should be displayed. Here's an example of setting font weight:



const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// Set font size, family, and weight
ctx.font = 'bold 30px Arial';
ctx.fillText('Hello, World!', 50, 50); // Render text at coordinates (50, 50)
 



In this example:

 
  • We use ctx.font = 'bold 30px Arial'; to set the font weight to bold along with the font size and family.
  • Then, we use ctx.fillText to render the text "Hello, World!" using the specified font weight.
  • Example with Multiple Customizations:
 

You can combine multiple customizations in the font property. Here's an example:



const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// Set font size, family, weight, and style
ctx.font = 'italic bold 30px Arial';
ctx.fillText('Hello, World!', 50, 50); // Render text at coordinates (50, 50)
 



In this example:
  • We use ctx.font = 'italic bold 30px Arial'; to set the font style to italic, font weight to bold, font size to 30 pixels, and font family to Arial.
  • Then, we use ctx.fillText to render the text "Hello, World!" with all specified font customizations.

 



Practice Excercise Practice now