How to Insert Line Breaks in HTML5 Canvas Using fillText Method
Written on
Adding Line Breaks to HTML5 Canvas
In certain scenarios, you might need to incorporate line breaks into the HTML5 canvas using the fillText method of the canvas context. This guide will demonstrate how to achieve this.
To start, we need to create the canvas element:
<canvas width='200' height='200'></canvas>
Next, we can access the canvas context with the following JavaScript code:
const c = document.querySelector('canvas').getContext('2d');
c.font = '11px Courier';
const txt = 'line 1nline 2nthird line..';
const x = 30;
const y = 30;
const lineheight = 15;
const lines = txt.split('n');
for (let i = 0; i < lines.length; i++) {
c.fillText(lines[i], x, y + (i * lineheight));
}
This code snippet sets up the canvas and prepares the text with line breaks.
Understanding the Code
First, we obtain the 2D context using querySelector and getContext. We then specify the font style we want to apply. The variable txt contains our text, which includes line breaks. The x and y variables are set to determine the starting position for the first line of text.
The split method is then utilized to divide the text into an array based on the line breaks. Finally, a loop is employed to render each line of text separately, adjusting the y-coordinate for each iteration by adding lineheight to ensure proper spacing.
Conclusion
By effectively splitting the text string based on line breaks and positioning each segment correctly, we can display multiple lines of text on the HTML5 canvas.