256 Chapter 10—Web Workers
In the JavaScript code, we first extract the altitude values from the PNG image. To
do this, we load the image into a new canvas element:
var canvas = document.createElement("CANVAS");
canvas.width = 300;
canvas.height = 300;
var context = canvas.getContext('2d');
var image = document.querySelector("IMG");
context.drawImage(image,0,0);
// document.querySelector(“BODY”).appendChild(canvas);
var elev =
context.getImageData(0,0,canvas.width,canvas.height).data;
var alpha = [];
for (var i=0; i<elev.length; i+=4) {
alpha.push(elev[i+3]);
}
In the variable image, the only img element on the website is loaded and then drawn
onto the newly created canvas element. Neither the image nor the canvas is vis-
ible on the website, because the img element is marked with display:none and the
canvas is never attached to the DOM tree. If you activate the commented-out line
in the preceding code, you can see the canvas at the end of the page. As you know
from Chapter 5, Canvas, the getImageData() function produces an array with the
color and alpha channel values of the canvas (in each case four entries per pixel).
Because only the alpha channel values are relevant for our example, we extract
them from the array via the for loop. This data reduction is sensible because each
worker receives a copy of the array. If we are starting four workers in parallel, the
memory usage increases linearly with each worker.
The calcProfiles() function then starts the calculation with or without workers,
depending on whether true or false is passed to the function:
calcProfiles = function(useWorker) {
USE_WORKER = useWorker;
startTime = new Date();
for (var i=0; i<PROFILES; i++) {
var imgData = {
id : i,
alpha: alpha,
parts : PARTS,
height : canvas.height,
width : canvas.width
}
The variable PROFILES contains the value of the relevant input field and controls
how often the central for loop is run. The imgData variable is created with the
altitude values of the image (alpha), the number of sections (PARTS), the canvas
height (height), and canvas width (width), plus an ID (id), with the latter being