Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text wrap in a <canvas> element

I am trying to add text on an image using the <canvas> element. First the image is drawn and on the image the text is drawn. So far so good.

But where I am facing a problem is that if the text is too long, it gets cut off in the start and end by the canvas. I don't plan to resize the canvas, but I was wondering how to wrap the long text into multiple lines so that all of it gets displayed. Can anyone point me at the right direction?

like image 756
Gwood Avatar asked May 29 '10 18:05

Gwood


People also ask

Can you do wrap around text in Canva?

With a smaller text box, your text will automatically wrap or overflow to the next line. Access our extended font library and upload your own fonts by subscribing to Canva Pro or Canva for Teams. They're also available to Canva for Education and Canva for Nonprofits users.

How do you wrap text in a drawing?

Wrap text around a picture or drawing objectSelect Format and then under Arrange, select Wrap Text. Choose the wrapping option that you want to apply.

How do you add text in canvas elements?

There are two method to build a text on Canvas, i.e. fillText() and strokeText(). fillText() method is used to make a text that can only be filled with color, whereas strokeText() is used to make a text that can only be given an outline color.


1 Answers

Updated version of @mizar's answer, with one severe and one minor bug fixed.

function getLines(ctx, text, maxWidth) {     var words = text.split(" ");     var lines = [];     var currentLine = words[0];      for (var i = 1; i < words.length; i++) {         var word = words[i];         var width = ctx.measureText(currentLine + " " + word).width;         if (width < maxWidth) {             currentLine += " " + word;         } else {             lines.push(currentLine);             currentLine = word;         }     }     lines.push(currentLine);     return lines; } 

We've been using this code for some time, but today we were trying to figure out why some text wasn't drawing, and we found a bug!

It turns out that if you give a single word (without any spaces) to the getLines() function, it will return an empty array, rather than an array with a single line.

While we were investigating that, we found another (much more subtle) bug, where lines can end up slightly longer than they should be, since the original code didn't account for spaces when measuring the length of a line.

Our updated version, which works for everything we've thrown at it, is above. Let me know if you find any bugs!

like image 77
crazy2be Avatar answered Oct 08 '22 17:10

crazy2be