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:
- Measuring the text's width and height
- 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.
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.
Finally, putting all this together I created a quick Text object for anyone to use/modd for their next HTML5 canvas game or app.