Pagini

Sunday, March 17, 2013

Bitmap fonts

Rendering images is far faster than rendering text with HTML5 canvas - this is not a canvas specific issue, most game APIs have the same issue. So since this is an old problem, it has an old solution: using bitmap fonts to compose text instead of regular fonts.

Bitmap fonts are simply collections of raster images of glyphs. For each variant of the font, there is a complete set of glyph images, with each set containing an image for each character. For example, if a font has three sizes, and any combination of bold and italic, then there must be 12 complete sets of images.
See bitmap fonts on Wikipedia.
The biggest advantaje of the bitmap fonts is that they are fast to draw, the biggest disadvantaje is that you'll need new bitmaps for each dimension, font style, etc.
The good news is that for our games we need a limited set of the font family(s), font size(s), etc, so we can happilly use custom generated bitmap fonts.

The plan

The plan is to generate two things:
  1. a big image with all the characters rendered using the font.
  2. a "map" file that indicates the place of each char image.

When we will need to render a word, like "Play", we'll do the following:
  1. Break the word in characters (e.g P, l, a and y).
  2. For each character, use the font map to get the char image position.
  3. Read the char image from the fonts image.
  4. Draw the char image on the canvas.

The conversion

Before we begin I must warn you that you should check if the licence of your favorite font allows you to do this. Let's begin.
  • Choose a font
    Download a font or choose one from your system. For example I used one from moorstation.org, one of my favorites, is called Die Deutsche Druckschrift .
  • Choose a tool
    Now as you image there are lots of tools for this job out there, both free and paid, so you can experiment with them for a while. I settled with fontbuilder - Bitmap font generator , an open source project. While there are executables only for Windows (at the moment), it runs with Wine on Mac OS X also.
    1. Select the font, size, etc:
    2. Select the character set:
    3. Select the layout of the generated image:
    4. Select the output folder:
    5. Convert XML to JSON. JavaScript likes JSON so we need to convert the XML to JSON (e.g. http://www.utilities-online.info/xmltojson/)

The usage

Once we have both the font image and the font map we need to load them in our game and we are ready to draw texts using them.
I've created a Bitmap font reader repo on Github that contains the JavaScript code, so if you're interested go ahead and have a look.
If everything works fine, you should see this in your browser:

Till next time: keep calm and don't forget to be awesome!

No comments:

Post a Comment