HTML and CSS Reference
In-Depth Information
We will discuss each of these attributes in detail in the upcoming section “Setting the
Text Font” on page 78 . All you need to know now is that a font designation of some
type is required. Here is a simple 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
context.fillStyle attribute and set it using a standard CSS color, or with a Canvas
Gradient 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.
Below 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.
Handling Basic Text in Text Arranger
For Text Arranger, we are going to allow the user to set the text displayed by the call
to context.fillText() . To do this, we will create a variable named message where we
will store the user-supplied text. We will later use that variable in our call to
context.fillText() , inside the standard drawScreen() method that we introduced in
Chapter 1 and will continue to use throughout this topic:
var message = " your text ";
...
function drawScreen() {
...
context.fillStyle = "#FF0000";
context.fillText (message, 100, 80);
}
To change the text displayed on the canvas to the text entered by the user, we need to
create an event handler for the text box keyup event. This means that whenever someone
changes text in the box, the event handler function will be called.
To make this work, we are going to name our text box in our HTML <form> using an
<input> form element. Notice that the id is set to the value textBox . Also notice that we
have set the placeholder="" attribute. This attribute is new to HTML5, so it might not
work in every browser. You can also substitute it with the value="" attribute, which
will not affect the execution of this application:
Search WWH ::




Custom Search