Categories
JavaScript Answers

How to Wrap Text in a Canvas Element with JavaScript?

Spread the love

To wrap text in a canvas element with JavaScript, we have to do the calculation for wrapping the text ourselves.

For instance, we write:

<canvas style='width: 300px; height: 300px'></canvas>

to create the canvas.

Then we write:

const wrapText = (ctx, text, x, y, maxWidth, lineHeight) => {
  const words = text.split(' ');
  let line = '';
  for (const [index, w] of words.entries()) {
    const testLine = line + w + ' ';
    const metrics = ctx.measureText(testLine);
    const testWidth = metrics.width;
    if (testWidth > maxWidth && index > 0) {
      ctx.fillText(line, x, y);
      line = w + ' ';
      y += lineHeight;
    } else {
      line = testLine;
    }
  }
  ctx.fillText(line, x, y);
}

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const maxWidth = 300;
const lineHeight = 24;
const x = (canvas.width - maxWidth) / 2;
const y = 70;
const text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc eu lacinia lorem, eget luctus odio. Pellentesque eget rhoncus eros. Suspendisse a finibus nisl, non porta erat. Donec interdum turpis ac urna egestas tempus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. ';

ctx.font = '15pt Calibri';
ctx.fillStyle = '#555555';
wrapText(ctx, text, x, y, maxWidth, lineHeight);

We create the wrapText function that takes the ctx canvas context.

text is the text to wrap.

x and y are coordinates of the top left corner of the text.

maxWidth is the max width of a line,

And lineHeight is the height of a line of text.

In the function, we split the text with split by a space into an array.

Then we loop through the returned string array entries with the entries method.

Next, we create a line of text with:

const testLine = line + w + ' ';

Next, we call ctx.measureText with testLine to get the dimensions of the text.

Then we have a if statement that checks if testwidth is bigger than maxWidth and index is bigger than 0.

If they’re both true, then we call fillText with the line then we set line to w + ' ' to get the text in the next line.

Then we have y += lineHeight to move the y coordinate of the text for the next line.

Otherwise, we don’t need to wrap the text and we set line to testLine.

Finally, we call ctx.fillText to draw the text.

Next, we get the canvas with querySelector.

Then we get the context with getContext.

And then we set the maxWidth of the text and the lineHeight.

Next, we calculate the x and y values of the top left corner of the text.

Then we set text to a string with the text we want to render.

And then we set the font and fillStyle of the text.

Finally, we call wrapText to draw the text.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

2 replies on “How to Wrap Text in a Canvas Element with JavaScript?”

Leave a Reply

Your email address will not be published.