HTML and CSS Reference
In-Depth Information
Remember that you need to make sure the window has finished loading and you need to
get a context object. Here's the full code for this example:
window.onload = function () {
var drawingSurface = document.getElementById("drawingSurface");
var ctxt = drawingSurface.getContext("2d");
ctxt.strokeText("1. Text with default font", 100, 100);
}
That's it. The strokeText call draws the specified text into the specified coordinates on the
canvas. The parameters specify what text to draw, and the (x,y) coordinates specify where
drawing should begin. The strokeText method draws in the default font style. You can easily
change the font property of the context object to enhance the appearance of your text. For
example, running the following code changes the font size to 24 and the font family to Arial:
ctxt.font = "24px arial";
ctxt.strokeText("2. Text with altered font", 100, 125);
To color your text, you could add this code:
ctxt.font = "24px arial";
ctxt.strokeStyle = "Red";
ctxt.strokeText("3. Text with altered colored font", 100, 160);
When you run the preceding code, notice that your text is outlined. This is the default
behavior when you increase the font size; it's drawn as outlined. To draw solid-colored text,
add the following code, which sets the illStyle property and calls the illText method instead
of the strokeStyle and StrokeText methods:
ctxt.font = "24px arial";
ctxt.fillStyle = "Red";
ctxt.fillText("4. Text with altered colored font", 100, 185);
You can also set the alignment of your text within the canvas. For example, to ensure your
text is centered, add this code:
ctxt.font = "24px arial";
ctxt.textAlign = "center";
ctxt.fillStyle = "Red";
ctxt.fillText("5. Text with altered colored font Centered.", drawingSurface.width / 2,
drawingSurface.height / 2);
By setting the textAlign property to the value center , you are telling the context to consider
the specified (x,y) coordinate as the center point of the string instead of the beginning point
of the string. So, you divide the canvas width and height by two to get the center point of the
canvas, and you get a string centered horizontally and vertically.
Figure 1-40 shows the progression of your text:
 
Search WWH ::




Custom Search