I had been having some difficulty working with fonts in Processing.js – I could not easily find information on how to solve my problems. This is a short post on the problem I had and the solution.
I wanted to position text within a circle such that the text was centred in the circle. This required knowing the width of the text and performing a simple calculation to determine where to position it relative to the centre of the circle. I did not know how to do this.
I found this post very quickly, which looked like it provided the solution. I tried out it a variant of it, but the text was not rendered in the correct position. It turned out that the width() function was returning a value of 0 all the time.
I don’t have excellent tools for debugging JS in general, or Processing.js in particular, so I was guessing somewhat. I figured that the loadFont() call was not actually loading the font correctly and hence no proper width calculation was performed. I tried to find some more info on font handling in Processing.js (although I must confess my knowledge of font handling in JS running in browsers is very limited).
Font handling in Processing.js seems to be still evolving. I found some recent postings in which Scott Downe’s was solving problems relating to custom fonts and Processing.js. I also found a discussion of font-handling by Eli Grey in which there is a link to a test of loadFont(), but it does not work in my browser (Chrome 5.0.375.126 on OS X).
I had assumed that the browser would be able to use fonts stored locally – I’m sure this is somehow possible, but I could not figure out how to do it easily. Most of the solution that I used was provided in this post – it describes how to create an SVG font which is stored on the server with the JS and is downloaded by the script as needed. As this solution involved storing the fonts on the server, I note how I did this using appengine here.
The solution that I used is the following:
- generate SVG variant of font using Batik as described here.
- use loadFont() with the full name (including the .svg extension) in the sketch – this will send a request to the server to obtain the SVG file – your server logs should show this request arriving at the server
- create a fonts directory in the appengine application; put the .svg font in this directory
- modify app.yaml to point requests for font.svg to a static file in the fonts directory
After I did this, loadFont() obtained the font from the server, the width() function worked and the text was rendered in the correct place within the circle.
I have no idea how to make Processing.js pick up default fonts stored on the client side using loadFont(). Any pointers on this welcome.