Categories
JavaScript Answers

How to Add Line Breaks into the HTML5 Canvas with fillText?

Spread the love

We can split the text string by the line breaks and position the split text in a way that each piece of text is on a separate line.

To do this, we write:

<canvas width='200' height='200'></canvas>

to add the canvas.

Then we write:

const c = document.querySelector('canvas').getContext('2d');
c.font = '11px Courier';
const txt = 'line 1\nline 2\nthird 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));
}

to add the txt text into the canvas.

We get the 2D context with querySelector and getContext .

Then we set the font property to the font we want.

Next, we have the txt text with some line breaks.

We set the x and y variables to the position of the text for the first line.

Then we call split to split txt by the line breaks into an array.

Finally, we use a for loop to call fillText on each lines entry with the y coordinates of the line incremented by each line with y + (i * lineheight) .

Now we should see each line of text display on its own line.

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 *