HTML and CSS Reference
In-Depth Information
Listing 4-10.
Drawing Text on the Canvas
var canvas = $("#MyCanvas").get(0);
var context = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height / 2;
context.font = "30px Arial";
context.textBaseline = "middle";
context.textAlign = "center";
context.lineWidth = 1;
context.strokeStyle = "red";
context.fillStyle = "blue";
context.strokeText("Hello Canvas!",x,y-50);
context.illText("Hello Canvas!",x,y+50);
This code sets the font for the text to be drawn using the
font
property. Note that the font size and
attributes such as bold and italics must be mentioned before the font family in order for the text to be
drawn correctly.
The
textBaseLine
property governs the baseline for the text. Some of the common values for
textBaseLine
property are
top
,
bottom
, and
middle
. These values affect the vertical positioning of the text
with respect to the y coordinate. For example, setting the
textBaseLine
property to
middle
means the text
is drawn with its vertical midpoint corresponding to the y coordinate. The
textAlign
property controls the
text alignment on the canvas. Common values for
textAlign
are
left
,
right
, and
center
. The
textAlign
property controls the alignment of the text with respect to the x position of the text. For example, if the x
coordinate is set to 100px and
textAlign
is set to
center
, then the center of the text is placed at 100px.
You can use the
strokeStyle
property to specify the text outline color. The
strokeText()
method
draws the text on the canvas with the specified
strokeStyle
.
The
fillStyle.
property governs how the text is filled, and the
fillText()
method draws the text with the
specified
fillStyle.
.
Figure 4-13 shows how the code from Listing 4-10 renders the specified text.
Figure 4-13.
The
strokeText()
and
fillText()
methods in action