Measuring Text:
Before aligning text, it's often necessary to measure the dimensions of the text to position it accurately. The measureText method in the canvas context (ctx) is used to measure the width of a given text string. Here's an example:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const text = 'Hello, World!';
const textMetrics = ctx.measureText(text);
const textWidth = textMetrics.width;
console.log('Text Width:', textWidth);
const ctx = canvas.getContext('2d');
const text = 'Hello, World!';
const textMetrics = ctx.measureText(text);
const textWidth = textMetrics.width;
console.log('Text Width:', textWidth);
In this example:
- We define a text string 'Hello, World!'.
- We use ctx.measureText(text) to measure the width of the text.
- The measured width is stored in textMetrics.width and can be used for alignment or other calculations.
Aligning Text:
Once the text width is known, it can be used to align text horizontally within the canvas. The textAlign property is used to set the horizontal alignment of text.
Here are the alignment options:
- 'left': Aligns the text to the left (default).
- 'center': Aligns the text to the center horizontally.
- 'right': Aligns the text to the right.
- Here's an example of aligning text to the center:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.font = '30px Arial';
ctx.textAlign = 'center'; // Align text to the center horizontally
ctx.fillText('Hello, World!', canvas.width / 2, canvas.height / 2); // Centered text
In this example:
- We set the font size and family using ctx.font.
- We set the horizontal alignment to center using ctx.textAlign = 'center';.
- The text 'Hello, World!' is rendered at the center of the canvas horizontally using ctx.fillText.
Vertical Alignment:
Vertical alignment of text can be achieved by adjusting the baseline using the textBaseline property. Here are the baseline options:
- 'top': Aligns the text to the top of the bounding box.
- 'middle': Aligns the text vertically centered.
- 'bottom': Aligns the text to the bottom of the bounding box.
- 'alphabetic': Aligns the text baseline with the alphabetic baseline.
- 'hanging': Aligns the text baseline with the hanging baseline.
- 'ideographic': Aligns the text baseline with the ideographic baseline.
Here's an example of vertically aligning text to the middle:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.font = '30px Arial';
ctx.textBaseline = 'middle'; // Align text vertically centered
ctx.fillText('Hello, World!', canvas.width / 2, canvas.height / 2); // Vertically centered text
In this example:
- We set the font size and family using ctx.font.
- We set the vertical alignment to middle using ctx.textBaseline = 'middle';.
- The text 'Hello, World!' is rendered at the middle of the canvas vertically.
Practice Excercise Practice now