Categories
JavaScript Answers

How to fix HTML5 canvas ctx.fillText not adding line breaks with JavaScript?

Spread the love

Sometimes, we want to fix HTML5 canvas ctx.fillText not adding line breaks with JavaScript.

In this article, we’ll look at how to fix HTML5 canvas ctx.fillText not adding line breaks with JavaScript.

How to fix HTML5 canvas ctx.fillText not adding line breaks with JavaScript?

To fix HTML5 canvas ctx.fillText not adding line breaks with JavaScript, we set the location of the text when we call fillText.

For instance, we write

const c = document.getElementById("c").getContext("2d");
c.font = "11px Courier";
console.log(c);
const txt = "line 1\nline 2\nthird line..";
const x = 30;
const y = 30;
const lineHeight = 15;
const lines = txt.split("\n");

for (const line of lines) {
  c.fillText(line, x, y + i * lineHeight);
}

to loop through the lines with a for-of loop.

In it, we call the context’s fillText method with the line to render.

Then y coordinates of the text is set to y + i * lineHeight which positions the text below the previous line.

Conclusion

To fix HTML5 canvas ctx.fillText not adding line breaks with JavaScript, we set the location of the text when we call fillText.

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 *