HTML and CSS Reference
In-Depth Information
<form>
Text: <input id="textBox" placeholder="
your text
"/>
<br>
</form>
Communicating Between HTML Forms and the Canvas
Back in our JavaScript code, we need to create an event handler for the
keyup
event of
textBox
. We do this by finding the form element using the
document.getElement
ById()
function of the DOM
document
object, and storing it in the
formElement
variable.
Then we call the
addEventListener()
method of
formElement
, setting the event to
keyup
and the event handler to the function
textBoxChanged
, which we have yet to
define:
var formElement = document.getElementById("textBox");
formElement.addEventListener('keyup', textBoxChanged, false);
The final piece of the puzzle is to define the
textBoxChanged()
event handler. This
function works like the event handlers we created in
Chapter 1
. It is passed one pa-
rameter when it is called, an
event
object that we universally name
e
because it's easy
to remember.
The
event
object contains a property named
target
that holds a reference to the HTML
form element that created the
change
event. In turn, the
target
contains a property
named
value
that holds the newly changed value of the form element that caused the
event to occur (i.e.,
textBox
). We retrieve this value, and store it in the
message
variable
we created in JavaScript. It is the very same
message
variable we use inside the
drawScreen()
method to paint the canvas. Now, all we have to do is call
draw
Screen()
, and the new value of
message
will appear “automagically” on the canvas:
function textBoxChanged(e) {
var target = e.target;
message = target.value;
drawScreen();
}
We just spent a lot of time describing how we will handle changes in HTML form
controls with event handlers in JavaScript, and then display the results on an HTML5
Canvas. We will repeat this type of code several more times while creating Text Ar-
ranger. However, we will refrain from explaining it in depth again, instead focusing on
different ways to render and capture form data and use it with Canvas.
Using measureText
The HTML5 Canvas context object includes a useful method,
measureText()
. When
supplied with a text string, it will return some properties about that text based on the
current context settings (font face, size, etc.) in the form of a
TextMetrics
object. Right
now the
TextMetrics
object has only a single property:
width
. The
width
property of a