HTML and CSS Reference
In-Depth Information
var myCanvas_context = my_canvas.getContext(“2d”);
myCanvas_context.strokeStyle = “#000000”;
myCanvas_context.fillStyle = “#FFFF00”;
myCanvas_context.fillStyle = “#000”;
myCanvas_context.font = “bold 36px sans-serif”;
myCanvas_context.fillText(“Welcome”, 75, 160);
To get the nice black text shown in Figure 28-8, I first needed to change the current fillStyle() . Then
the font() function sets the font-weight (bold), size (36px), and font (sans-serif). Finally, the fillText()
function specifies the string to put on the canvas as well as the starting x and y coordinates.
FiGure 28-8
Because the length of the text string as drawn on the canvas is not immediately obvious, finding those
starting points to get a perfectly centered element can require a good deal of trial and error. Luckily,
the JavaScript API includes two text-related functions that can simplify the process: textAlign() and
textBaseline() . With possible values of start , end , left , right , and center , the textAlign()
function is like, but not exactly the same, as the CSS text-align property. The textBaseline()
function determines where the text is drawn relative to the starting coordinates; possible values for
this function are top , hanging , middle , alphabetic , ideographic , and bottom .
Putting the textAlign() and textBaseline() functions to work, you can align your text by set-
ting the starting point to the center of the canvas as shown in Figure 28-9 with the following code,
even when you change the text:
<script type=”text/javascript”>
Search WWH ::

Custom Search