Using fillText Method:
The fillText method is used to render filled text on the canvas. It takes several parameters:
text: The text string to be rendered.
- x: The x-coordinate of the starting point for the text.
- y: The y-coordinate of the starting point for the text.
- Optional: maxWidth - Maximum width for the text to be rendered. If provided, the browser will adjust the text to fit within this width.
Here's an example of how you can use fillText:
const context = canvas.getContext('2d');
context.font = '30px Arial'; // Set the font size and type
context.fillStyle = 'red'; // Set the text color
context.fillText('Hello, World!', 50, 50); // Render filled text at coordinates (50, 50)
In this example:
- We set the font size and type using context.font.
- The text color is set using context.fillStyle.
- Then we use context.fillText to render the text "Hello, World!" at coordinates (50, 50) on the canvas.
Using strokeText Method:
The strokeText method is used to render outlined (stroked) text on the canvas. It also takes similar parameters as fillText:
text: The text string to be rendered.
x: The x-coordinate of the starting point for the text.
y: The y-coordinate of the starting point for the text.
Optional: maxWidth - Maximum width for the text to be rendered.
Here's an example of using strokeText:
const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
context.font = '30px Arial'; // Set the font size and type
context.strokeStyle = 'blue'; // Set the text outline color
context.lineWidth = 2; // Set the outline width
context.strokeText('Hello, World!', 50, 50); // Render stroked text at coordinates (50, 50)
In this example:
- We set the font size and type using context.font.
- The text outline color is set using context.strokeStyle.
- context.lineWidth sets the width of the outline.
- We use context.strokeText to render the text "Hello, World!" with an outline at coordinates (50, 50) on the canvas.
Example with Both fillText and strokeText:
You can combine fillText and strokeText to create text with both filled and outlined appearance:
const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
context.font = '30px Arial'; // Set the font size and type
context.fillStyle = 'red'; // Set the fill color
context.strokeStyle = 'blue'; // Set the outline color
context.lineWidth = 2; // Set the outline width
context.fillText('Hello, World!', 50, 50); // Render filled text at coordinates (50, 50)
context.strokeText('Hello, World!', 50, 50); // Render stroked text at coordinates (50, 50)
This code will render the text "Hello, World!" on the canvas with a red fill color and a blue outline.
Practice Excercise Practice now