🚧 WIP - Come back soon! 🚜

The JavaScript Canvas API comes “batteries not included”. As a relatively low-level API, it often requires third-party libraries to work with even simple graphics. However, one of the greatest pain points of the API is it’s rudimentary text-formatting capabilities.

If you have ever tried rendering “Hello World” onto an HTML canvas, on your first attempt, you probably drew something like this:

(The text is off-screen.)

But after messing around with the CanvasRenderingContext2D font and textBaseline properties and text placement, you likely arrived at something like this:

And you probably thought That looks great, I’m getting the hang of this!, but then you tried to render arbitrary text:

On a wide enough screen, this might look fine and you’d perhaps never notice an issue. But for those on smaller devices or who try a longer input text, they see the text clipped.

Unfortunately, if you want to format text into some fixed region of the canvas, the Canvas API is limited in its capabilities. Even if you’re clever and have already figured out text wrapping, you can still run out of vertical space or even have single words that are too long.

You’re probably thinking, Well that’s kind of frustrating. It should be easier,, and you’re right. However, the manual solution actually lends a rather elegant algorithm.


I personally had a use case for the algorithm when I was developing Mocking SpongeBob Meme Generator. The goal for that project was to be able to generate and send memes as quickly as possible, and doing so required automatically formatting the caption for the user into a fixed region of the image.

A GIF demoing the formatting algorithm in Mocking SpongeBob Meme Generator.

While this was one of my more silly projects, it came with a lot of interesting UI/UX challenges that probably deserve a blog post of their own. However, the most difficult challenge to solve by far was the automatic layout algorithm.

To be Continued