HTML and CSS Reference
In-Depth Information
Drawing text on the
<canvas>
is easy with the
fillText
method:
function draw(){
var canvas = document
.getElementById('mycanvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.fillText(
'HAI! IZ IN YR ELEMENT
WRITIN YR TXT',
10,10);
}
}
The
fillText
method has three required
parameters: a string that is the text to be
drawn, and x and y coordinates to deter-
mine where it's to be drawn.
The text is drawn in the current font, which is determined by setting
the
font
property of the drawing context. The
<canvas>
element's
font
property behaves like the
CSS
font
property, allowing size and font to
be specified simultaneously:
ctx.font = "10pt serif";
If you set the font size a little larger, you can see an alternative method
for drawing text. As with rectangles, you can draw the fill and the
stroke separately:
function draw(){
var canvas = document
.getElementById('mycanvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.font = "12pt sans-serif";
ctx.fillText(
'HAI! IZ IN YR ELEMENT
WRITIN YR TXT',
10,20);
ctx.strokeText(
'HAI! IZ IN YR ELEMENT