HTML and CSS Reference
In-Depth Information
codea;
case b:
codeb;
default: codec;
}
JavaScript evaluates the value of
x
in the first line of the
switch
statement and compares it to the values
indicated in the cases. Once there is a hit, that is,
x
is determined to be equal to
a
or
b
, the code following
the
case
label is executed. If there is no match, the code after
default
is executed. Its not necessary to
have a default possibility. Left to its own devices, the computer would continue running through the
switch
statement even if it found a matching
case
statement. If you want it to stop when you find a
match, you need to include a
break
statement to break out of the switch.
You can probably see already how
if
and
switch
will do what we need for the dice game. Youll read how
in the next section. First, lets look at an example that determines the number of days in the month
indicated by the variable
mon
holding three-letter abbreviations ("Jan", "Feb", etc.).
switch(mon) {
case "Sep":
case "Apr":
case "Jun":
case "Nov":
alert("This month has 30 days.");
break;
case "Feb":
alert("This month has 28 or 29 days.");
break;
default:
alert("This month has 31 days.");
}
If the value of the variable
mon
is equal to
"Sep"
,
"Apr"
,
"Jun"
, or
"Nov"
, control flows to the first
alert
statement and then exits the
switch
statement because of the
break
. If the value of the variable
mon
is
equal to
"Feb",
the
alert
statement mentioning 28 or 29 days executes and then the control flow exits
the
switch
. If the value of
mon
is anything else, including, by the way, an invalid three-letter abbreviation,
the
alert
mentioning 31 days is executed.
Just as HTML ignores line breaks and other white space, JavaScript does not require a specific layout for
these statements. You could put everything on one line if you wished. However, make things easy on
yourself and use multiple lines.
Drawing on the canvas
Now we get to one of the most powerful new features in HTML5, the
canvas
element. I will explain the
pieces of coding that go into an application involving
canvas
, then show some simple examples, and
finally get back to our goal of drawing dice faces on the canvas. Recall that the outline for an HTML
document is
<html>
<head>
<title>… </title>