Canvas text rendering
23 June 2009, 19:51
HTML 5 Canvas specification defines two important methods for text rendering:
strokeText(). You also have a
measureText() and the associated text-related
properties: font, textAlign and
The Canvas Text API is only implemented in Webkit (Safari and Chrome) and in Gecko 1.9.1+ (Firefox 3.5+).
If you want to render text in your Canvas element in Gecko 1.9.0 (Firefox 3.0) you can use their proprietary Canvas text rendering API which is now, obviously, deprecated in favour of the standardized API. They provided the following methods:
mozMeasureText(). To style the text you only have the mozTextStyle
In PaintWeb I use the
mozPathText() method when the standard
API is not available.
Opera does not support the Canvas Text API. I learned that the
drawImage() 2D context method allows the drawing of SVG document as well - this works only in Opera. I implemented
the text tool by adding a new minimal SVG document which contains a
<text> element. This was updated and drawn in the Canvas element in sync with user interaction. However,
after I completed the implementation I found several bugs:
- SVG redraw issues. When you update the text styling properties, or when you update the text itself, sometimes Opera fails to entirely redraw the SVG document, irrespective of the SVG being visible or not.
memory leaks (test case). For some unfortunate reason, each
drawImage(svgDocument)leaks some amount of memory. Got a crasher with this, and a system freeze after filling my physical memory (1 GB) and the swap (1 GB). ;)
security violations (test case). Opera considers the SVG
document as being an external resource, thus it marks the Canvas as being "dirty" once
drawImage(svgDocument)is invoked. You can no longer read pixels using
getImageData(), nor can you use the
toDataURL()method. This broke the PaintWeb history mechanism, the selection tool, and the "image save" option.
The first two issues I said I can live with, but not with the security violations. Thus, I have disabled the text tool in Opera. I have reported the last two bugs to Opera with the associated minimal test cases.
If you are interested to render text, you can even attempt server-side "hacks". You could make a server-side script which renders text, and you can then draw it in your Canvas with an image element. This, however, defeats the purpose of PaintWeb - I want it to be a "pure" client-side Web application.
Lastly, you can implement "vector drawing" of text using a client-side font definition in some format, and then render it with basic paths in Canvas. Again, this is beyond the purpose of PaintWeb. Opera will implement Canvas Text some day. :)
For further details about attempts at rendering text when the standard Canvas Text API is not available, please read the rendering text blog post wrote by Christopher Clay at the end of 2006.