HTML and CSS Reference
In-Depth Information
In the canvasApp() function, we will define a variable named fillOrStroke that we will
use to hold the value selected by the user on the HTML <form> . The default value will
be fill , which means Text Arranger will always show fillText first:
var fillOrStroke = "fill";
We will also create the event listener for a change in the fillOrStroke form element…
formElement = document.getElementById("fillOrStroke");
formElement.addEventListener('change', fillOrStrokeChanged, false);
…and create the function fillOrStrokeChanged() to handle the event:
function fillOrStrokeChanged(e) {
var target =;
fillOrStroke = target.value;
While we created a separate function for each event handler for the applications in this
chapter, in reality many of them work in an identical way. However, some developers
might be inclined to use an eval() function, such as the following, as their event handler
for changes made to the HTML element that controls Text Arranger:
var formElement = document.getElementById("textBox");
formElement.addEventListener('keyup', function(e) {
applyChange('message', e) }, false);
formElement = document.getElementById("fillOrStroke");
formElement.addEventListener('change', function(e) {
applyChange('fillOrStroke', e) }, false);
function applyChange (variable, e) {
eval(variable + ' =');
The code above uses eval() to create and execute JavaScript code on the fly. It dynam-
ically creates the name of the HTML element so that the multiple event handler func-
tions do not need to be created individually. However, many developers are wary of
using eval() because it opens up security holes, and makes debugging code more
difficult. Use at your own risk.
In the drawScreen() function, we test the fillOrStroke variable to see whether it con-
tains the value fill . Since we have three states ( fill , stroke , or both ), we use a
switch statement to handle the choices. If the choice is both , we set the strokeStyle to
black ( #000000 ) as the highlight for the colored fillText .
If we use the xPosition and yPosition calculated using the width and height of the
canvas, the message variable that contains the default or user-input text, and the fill
OrStroke variable to determine how to render the text, we can display the text as con-
figured by the user in drawScreen() :
Search WWH ::

Custom Search