HTML and CSS Reference
In-Depth Information
Rendering text
The canvas allows you to render text on to the canvas and
specify fonts, sizes, alignment, and baselines. You can also fi ll
text (as normal text might appear) and stroke text (for example,
around the outline). Bespin ( https://bespin.mozillalabs.com ) is
a great example of how custom text rendering can be used to
create a fully functional code editor entirely written using the
canvas API.
Drawing text requires the string and coordinates. For example,
to show you how to use translate , I used an annotated canvas
(shown in Figure 5.19 and also earlier in this chapter in Figure
5.13). I used fillText to annotate the new centre point of the
canvas to label the dots I had placed around the canvas (whose
height and width are hard coded to 300x300 for this example):
function dot(string) {
ctx.beginPath();
ctx.arc(0,0,5,0,Math.PI*2,true); // draw circle
ctx.fill();
ctx.fillText(string, 5, 10); // render text
}
Now I can translate the canvas and call the dot function, passing
the string I want printed next to the dot:
dot('1. no translate'); // show dot
ctx.translate(150, 150);
dot('2. (150, 150)'); // show dot
ctx.translate(-100, 20);
dot('3. (-100, 20)'); // show dot
FIGURE 5.19 Using fillText to
annotate a canvas.
 
Search WWH ::




Custom Search