10.3 Calculate Altitude Profiles with Canvas 253
$("y").innerHTML = evt.data.substr(2);
} else {
$("cnt").innerHTML += "Leap year: "+evt.data+"\n";
}
}
The substr() function extracts the first two characters of the variable evt.data
and compares them to the value "y ". In the case of a match, the field for display-
ing the date is updated; otherwise, the date is added as a new line to the field with
the ID cnt. As in many other examples, we use the $() function as an abbrevia-
tion for the document.getElementById() call.
If the worker takes too long to run (for example, if your computer does not com-
pute fast enough), you can force the process to end by clicking the Stop button.
This stops the worker via the terminate() function; thereafter, the Start button is
reactivated after being inactive during the computation:
stopCalc = function() {
w.terminate();
$("start").removeAttribute("disabled");
}
The next, more extensive example shows how several workers can work in paral-
lel and carry out a more practical computation than the previous one.
10.3 Calculate Altitude Profiles with Canvas
Among the areas where web workers are particularly useful is undoubtedly the
client-side analysis of audio, video, and image files. In our example, we use a
PNG file showing the area of Tyrol, Austria, with a special feature: The image’s
alpha channel contains the altitude information of the area. You can find this
image online at
http://html5.komplett.cc/code/chap_workers/images/topo_elevation_alpha.png.
Via canvas we can not only read the color values, but also the alpha channel val-
ues (see Chapter 5, Canvas), allowing us to carry out computations regarding
the region. One simple example for such a computation is an altitude profile,
extracting the altitude value for each point along a certain line.
The profiles in our example consist of several sections, and we can set both the
number of the sections and the number of profiles via text fields on the website.
This is necessary to be able to adapt the computation to computers of differ-
ent speeds. The individual profile sections result from randomly chosen points
within the picture. We want the program to display a progress bar during the