Getting Text into a WebGL Texture

Posted on August 12, 2013 | Comments Off

While working on KontikiJS I came across the need to be able to write formatted text into a texture to use with WebGL. You can do this in JavaScript with a bit of work. This is done with the Canvas’s fillText API. The trick is to measure what the text so you can create the Canvas with the right width and height.

There are 2 approaches to measuring the text size. The first is set up the font styling on the Canvas and then call measureText(text). But measureText() returns an object that has the width only. You then use the font size as you height, which is not always correct. Here is some JavaScript that shows what this would look like:

The second method is a bit more complex but can give you a better width and height of the bounding box. This bounding box includes all the styles. To do this what you do is render the text in a hidden div and call clientWidth/clientHeight on the div. Here is what the JavaScript might look like: