How to use BMFont (Bitmap Font Generator) in Three.js by Shu Miyao

Posted on 7 July, 2017


Showing font in three.js is not easy as much as 2d frameworks. There may be numbers of ways to show text, what I could find are:

  1. Use BMFont
  2. Use typeface.js fonts (here is a sample but please be advised that the pen is really slow.)

I tried both of above, I ended up with the BMFont option because it is quite light and works faster. Yet I really liked how text characters shown with the typeface.js option looks in 3d.

Here is a small sample script to show how to show BMFont text in three.js.

The sample code above used information from Rendering Text in WebVR By David Lyons, Lead WebVR Developer, Within. The code depends on 1: three.min.js, 2: OrbitControls.js, 3: three-bmfont-text-bundle.js, 4: sdf-shader.js, and 5: text-bitmap.js. The loaded js files can be checked up in the Pen Settings / JavaScript of the sample pen above.

A rough guide of procedures to use BMFont is as follows:

  1. You need to prepare a font file. There are numbers of options. For MacOS, there are software called Glyph Designer or bmGlyph. For a cross platform solution, Hiero is available as it runs on java. You will produce a png file and an accompanying json file for your font.
  2. Load the font file dynamically with XMLHttpRequest (see loadFont() function in the sample code above.) Parse a received json text data and set that to a variable.
  3. Create an instance of TextBitmap class. Set a url path to the font image to the imagePath property. The “font” property needs the font data set in the step #2 above.
  4. Add the group property of TextBitmap class instance made in the step above to the scene. (for the steps from #3~#4, please refer to createTextLine() function to roughly see how it is done.
  5. To change the text, set a text string to the text property. See generateRandomTestPattern() function.

This might not be the best sample but I hope that you get an idea of what to do with BMFont in Three.js.

Thank you for reading!