10.3 Calculate Altitude Profiles with Canvas 257
required as reference for the profiles. Then the program logic divides itself into
the part working with web workers and the part without web workers:
if (USE_WORKER) {
imgData.useWorker = true;
var worker = new Worker('canvas_profile.js');
worker.postMessage(imgData);
worker.onmessage = function(evt){
if (evt.data.task == 'update') {
progress.item(evt.data.id).value = evt.data.status*i;
} else if (evt.data.task == 'newMin') {
$('progDivMin'+evt.data.id).innerHTML = evt.data.min;
} else if (evt.data.task == 'newMax') {
$('progDivMax'+evt.data.id).innerHTML = evt.data.max;
} else {
showResults(evt);
}
};
}
else {
imgData.useWorker = false;
showResults(
onmessage({data:imgData})
);
progress.item(i).value = PARTS;
}
In the first case, a new worker is created and activated with postMessage(). The
entire data structure of the imgData variable is passed to it. Then an event listener
is defined, which receives four different message types. Messages of the type up-
date will update the progress bar, and newMin and newMax reset the relevant alti-
tude values on the website. All other messages call the showResult() function,
which works out the time of the calculation and displays it with the number of
points on the altitude profile.
If the call is to be started without workers, the onmessage() function of the ex-
ternal JavaScript file is started, with the imgData variable wrapped into the data
attribute of a JavaScript object. This is useful because the postMessage() call in
the worker also wraps data into such a structure, and we therefore do not need to
further adapt the external code.
The external JavaScript file canvas_profile.js starts with the onmessage() function.
In the notation shown here, this function has a double purpose: as an event han-
dler for the worker’s message event and also as a global function, which we can call
without a worker. In it, the random points for the individual sections are created:
onmessage = function(evt) {
...
var p1 = [Math.round(Math.random()*(evt.data.width-1)),