HTML and CSS Reference
In-Depth Information
Communicating Between HTML Forms and the Canvas
Back in our JavaScript code, we need to create an event handler for the
keyup
event of
tex-
tBox
. We do this by finding the form element by using the
document.getElementById()
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
var
formElement
=
document
.
getElementById
(
"textBox"
);
formElement
.
addEventListener
(
'keyup'
,
textBoxChanged
,
false
false
);
The final piece of the puzzle is to define the
textBoxChanged()
event handler. This function
called, an
event
object that we universally name
e
because it's easy to remember.
The
event
objectcontainsapropertynamed
target
thatholdsareferencetotheHTMLform
element that created the
change
event. In turn, the
target
contains a property named
value
that holdsthenewlychanged value oftheformelement that caused theevent tooccur(that is,
textBox
).Weretrievethisvalueandstoreitinthe
message
variablewecreatedinJavaScript.
Itistheverysame
message
variableweuseinsidethe
drawScreen()
methodtopaintthecan-
vas. Now, all we have to do is call
drawScreen()
, and the new value of
message
will appear
“automagically” on the canvas:
function
function
textBoxChanged
(
e
) {
var
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 Arranger. However, we will
refrainfromexplainingitindepthagain,insteadfocusingondifferentwaystorenderandcap-
ture form data and use it with Canvas.