HTML and CSS Reference
In-Depth Information
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 earlier 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.
By default, the fillText method uses a 10 pixel tall sans serif
as the selected font. You can change this to your own font
style by setting the font property on the context using the
same syntax as CSS fonts (for example, ctx.font = 'italic 400
12px/2 helvetica neue, sans-serif' ). You can even use CSS3
web fonts, provided they've been fully loaded before you use
them. When I call fillText , the text rendering uses the same
fillStyle that I set earlier (or uses the canvas default). Equally
strokeText uses the current strokeStyle .
 
Search WWH ::




Custom Search