HTML and CSS Reference
In-Depth Information
You can specify the font, font style, and size using the contexts
font
property:
ctx.font = “Bold 32px Georgia";
The text alignment can be set using the
textAlign
property:
ctx.textAlign = “center";
For the text color, use the
fillStyle
property you learned about earlier in this chapter.
Now that you know the basics of how to add text to your canvas, let's write some more code.
The code in this exercise can be found in folder 5.
Follow these steps to add the text:
1.
Open the
adscript.js
in your text editor.
2.
Set the font to
Bold 32px Georgia
.
function drawAdvert() {
...
// Add the text styling
ctx.font = “Bold 32px Georgia";
}
3.
Set the text alignment to
center
.
function drawAdvert() {
...
// Add the text styling
ctx.font = “Bold 32px Georgia";
ctx.textAlign = “center";
}
4.
Set the text color to
#FFFFFF
(white).
function drawAdvert() {
...
// Add the text styling
ctx.font = “Bold 32px Georgia";
ctx.textAlign = “center";
ctx.fillStyle = “#FFFFFF";
}
5.
Now you need to calculate the
x
and
y
coordinates for the text. For the
x
coordinate, divide the canvas
width by two to get the center point and then subtract 80 in order to move everything slightly to the left. Ini-
tialize a new variable called
textX
with the result: