Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
143023864X_HT5.pdf
Скачиваний:
8
Добавлен:
21.02.2016
Размер:
7.98 Mб
Скачать

CHAPTER 10 USING THE WEB WORKERS API

addEventListener("message", messageHandler, true);

Listing 10-9. Content of the File blur.js

function inRange(i, width, height) {

return ((i>=0) && (i < width*height*4));

}

function averageNeighbors(imageData, width, height, i) { var v = imageData[i];

// cardinal directions

var north = inRange(i-width*4, width, height) ? imageData[i-width*4] : v; var south = inRange(i+width*4, width, height) ? imageData[i+width*4] : v; var west = inRange(i-4, width, height) ? imageData[i-4] : v;

var east = inRange(i+4, width, height) ? imageData[i+4] : v;

// diagonal neighbors

var ne = inRange(i-width*4+4, width, height) ? imageData[i-width*4+4] : v; var nw = inRange(i-width*4-4, width, height) ? imageData[i-width*4-4] : v; var se = inRange(i+width*4+4, width, height) ? imageData[i+width*4+4] : v; var sw = inRange(i+width*4-4, width, height) ? imageData[i+width*4-4] : v;

// average

var newVal = Math.floor((north + south + east + west + se + sw + ne + nw + v)/9);

if (isNaN(newVal)) {

sendStatus("bad value " + i + " for height " + height); throw new Error("NaN");

}

return newVal;

}

function boxBlur(imageData, width, height) { var data = [];

var val = 0;

for (var i=0; i<width*height*4; i++) {

val = averageNeighbors(imageData, width, height, i); data[i] = val;

}

return data;

}

Summary

In this chapter, you have seen how Web Workers can be used to create web applications with background processing. This chapter showed you how Web Workers (and inline and shared Web Workers) work. We discussed how you can use the APIs to create new workers and how you

261

CHAPTER 10 USING THE WEB WORKERS API

communicate between a worker and the context that spawned it. Finally, we showed you how you can build an application with Web Workers. In the next chapter, we’ll demonstrate more ways that HTML5 lets you keep local copies of data and reduce the amount of network overhead in your applications.

262