Text rendering on a 2D canvas context can be a bit tricky when trying to cache the rendered text to an offscreen canvas. The following challenges have to be solved in order to cache the rendered text correctly:

  1. Measuring the text's width and height
  2. Moving the registration point of the text to its top left corner

The first challenge turns out to be quite simple if you resort to some DOM manipulation.

The second challenge is a bit more illusive. First you might think to simply offset the text by its height, thereby placing its registration point at the top left corner of the text instead of its bottom left corner like it normally is. But this will result in your decending text being clipped by your cached canvas.

Notice that the decending part of the 'g' characters are being cut off by our buffer.

To resolve this, set the textBaseline property to middle before rendering your text then render your text with a y offset of half its height.

After setting 'textBaseline' to 'middle' and offseting the text 'y' by half its height our text is not cut off and fills the buffer correctly.

Finally, putting all this together I created a quick Text object for anyone to use/modd for their next HTML5 canvas game or app.