HTML and CSS Reference
In-Depth Information
Basic Text Display
Thesimplestwaytodefinetexttobedisplayedonthecanvasistosetthe
context.font
style
by using standard values for CSS font style attributes:
font-style
,
font-weight
,
font-
size
, and
font-face
.
Wewilldiscusseachoftheseattributesindetailintheupcomingsection
SettingtheTextFont
.
All youneed toknownowisthat afontdesignation ofsome type isrequired. Here isasimple
example of setting a 50-point serif font:
context
.
font
=
"50px serif"
;
You also need to set the color of the text. For filled text, you would use the
con-
text.fillStyle
attribute and set it using a standard CSS color, or with a
CanvasGradient
or
CanvasPattern
object. We will discuss the latter two options later in the chapter.
Finally, you call the
context.fillText()
method, passing the text to be displayed and the
x
and
y
positions of the text on the canvas.
The following is an example of all three basic lines of code required to display filled text on
HTML5 Canvas:
context
.
font
=
"50px serif"
context
.
fillStyle
=
"#FF0000"
;
context
.
fillText
(
"Hello World"
,
100
,
80
);
If you do not specify a font, the default 10px sans-serif will be used automatically.