Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

488 CHAPTER 12 Drawing with HTML5


Drawing text


You can also draw text on the canvas by using the fillText or strokeText method. Support
for drawing text is somewhat basic. Both methods require you to pass the text to be drawn
as the first parameter, followed by x and y coordinates that specify where the text is drawn.
The exact meaning of the coordinate depends on the value of the textAlign and textBaseline
properties, but the default is that the coordinate is at the lower-left corner of the text that’s
drawn. You can also provide a parameter to indicate the maximum width of the text to be
drawn.
In addition to the methods, the following properties can be set to control the look of the
rendered text.
■■font Sets the font style, size, and family, delimited by spaces. The style can be nor-
mal, italic, or bold. The size can be a CSS size. The family represents the font family,
which can be a generic font family, such as serif or sans serif, or a specific font family,
such as Arial or Courier.
■■textAlign Sets the horizontal alignment of the text in relation to the coordinate that
is passed into the fillText or strokeText method. Can be start, end, left, right, or center.
Note that start and left are the same, and end and right are the same.
■■textBaseline Sets the vertical alignment of the text in relation to the coordinate that
is passed into the fillText or strokeText method. Can be top, hanging, middle, alpha-
betic, ideographic, or bottom.
The following example code draws a line across the canvas, through its center point
(400, 300). After that, “Hello” is drawn using the coordinate of 400, 300.
function drawText() {
var canvas = document.getElementById('myCanvas')
, ctx = canvas.getContext('2d');

ctx.strokeStyle = 'magenta';
ctx.fillStyle = 'yellow';
ctx.lineWidth = 2;
ctx.font = “bold 100pt TimesNewRoman";

ctx.beginPath();
ctx.moveTo(100, 300);
ctx.lineTo(700, 300);
ctx.stroke();

ctx.strokeStyle = 'blue';
ctx.fillText(“Hello", 400, 300);
ctx.strokeText(“Hello", 400, 300);
}
Free download pdf