CHAPTER 8
used. This complexity is forced on us because the browsers implement event handling using different
terms.
function choose(ev) {
var mx;
var my;
if ( ev.layerX || ev.layerX == 0) {
mx= ev.layerX;
my = ev.layerY;
} else if (ev.offsetX || ev.offsetX == 0) {
mx = ev.offsetX;
my = ev.offsetY;
}
The goal of this portion of the code is to make the variables mx and my respectively hold the horizontal and
vertical coordinates for the mouse cursor when the mouse button is clicked. Certain browsers keep the
cursor information in properties of the ev parameter named layerX and layerY and others use offsetX
and offsetY. We will use local variables to make sure we track the cursor position across all browsers.
The condition ev.layerX will evaluate as false if ev.layerX does not exist for this browser or if it does
exist and has the value 0. Therefore, to check if the property exists, we need to use the compound
condition (ev.layerX || ev.layerX == 0) to make sure the code works in all situations. By the way,
if the second if test fails, nothing happens. This code works for Chrome, Fi reFox, and Safari, but
presumably will work eventually with all browsers.
The next section of code iterates through the elements of everything (there are three elements, but
thats not mentioned explicitly) to see if the cursor is on any of the rectangles. The variable ch holds a
reference to a Throw and so all the Throw attributes, namely, sx, sy, bwidth, and bheight, can be used
in the compare statements. This is shorthand for all the choices of throws held in the everything array.
var i;
for (i=0;i<everything.length;i++){
var ch = everything[i];
if ((mx>ch.sx)&&(mx<ch.sx+ch.bwidth)&&(my>ch.sy)&&(my<ch.sy+ch.bheight)) {
...
break;
}
}
The ... indicates coding to be explained later. The compound condition compares the point mx,my with the
left side, right side, top, and bottom of the outer rectangle of each of the three objects representing
possible throws by the player. Each of these four conditions must be true for the point to be within the
rectangle. This is indicated by the && operator. Though long, this is a standard way to check for points
inside rectangles and you will become accustomed to using it.
So thats how the graphics are drawn on the canvas and how they serve as buttons. Notice that if the
player clicks outside of any button, nothing happens. Some people might recommend providing feedback
to the player at this point, such as an alert box saying:
Please make your move by clicking on the rock, paper, or scissors!
Others would tell you to avoid cluttering on the screen and assume that the player will figure out what to
do.