Recently I had a small requirement for a project I am currently working at in my spare time: centralize a text inside a given rectangular area (if I already know the x, y, w, h dimensions of the rectangle).

The main idea was to use the context.measureText(text).width; method, as it returns the width of the specified text in pixels – exactly what I needed.

Eventually I’ve came up with the following code:

And I thought it was working perfectly:

… until I realized that I have to find a way to wrap the text inside. After some few refinements the new paint_centered method is:

The new refined paint_centered_wrap method is more or less the same as the initial one (the logic is the same), but with one important addition: we split the text to be painted into an array of strings, each element of this array having it’s width smaller than than the width of the rectangle. Take a look at the inner function called split_lines – that’s the one responsible with the “intelligent” string splitting.

The results are now more or less as we expected:

3 thoughts on “Painting and wrapping a text inside a rectangular area (html5 canvas)

  1. This is nice.
    One thing I do not understand though:

    in the for loop you are redefining ly
    any reason for that?

    • No, I believe it was a mistake. There’s no reason for that. I believe you can remove ly from the loop.

      Like this:

  2. Hello, thanks for the useful post…it helped me lot but it was not handling a scenario where the rectangle are vertical….I have modifed your code logic to handle that…


Leave a reply

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url=""> 


Are we human, or are we dancer *