-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinnerWorker.js
72 lines (58 loc) · 1.69 KB
/
innerWorker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
onmessage = (e) => {
const getSingleRGBA = (rgbaData) => {
const length = rgbaData.length;
const valueOccurence = length / 4;
let i = 0;
let r = 0,
g = 0,
b = 0,
a = 0;
while (i < length) {
[r, g, b, a] = [
r + rgbaData[i],
g + rgbaData[i + 1],
b + rgbaData[i + 2],
a + rgbaData[i + 3],
];
i += 4;
}
r = Math.floor(r / valueOccurence);
g = Math.floor(g / valueOccurence);
b = Math.floor(b / valueOccurence);
a = Math.floor(a / valueOccurence);
return [r, g, b, a];
};
const [
imageBitmap,
width,
height,
outerValue,
isGrayScale,
innerValues,
shouldAllocateByRows,
] = e.data;
const canvas = new OffscreenCanvas(width, height);
const ctx = canvas.getContext("2d", {
willReadFrequently: true,
});
ctx.drawImage(imageBitmap, 0, 0);
let innerDimension = 0;
for (const innerValue of innerValues) {
const [x, y, sectionWidth, sectionHeight] = shouldAllocateByRows
? [innerDimension, 0, innerValue, outerValue]
: [0, innerDimension, outerValue, innerValue];
const imageData = ctx.getImageData(x, y, sectionWidth, sectionHeight);
const [r, g, b, a] = getSingleRGBA(imageData.data);
if (isGrayScale) {
// luminance formula
const luminance = 0.299 * r + 0.587 * g + 0.114 * b;
ctx.fillStyle = `rgba(${luminance}, ${luminance}, ${luminance}, ${a})`;
} else {
ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${a})`;
}
ctx.fillRect(x, y, sectionWidth, sectionHeight);
innerDimension += innerValue;
}
const resultBitmap = canvas.transferToImageBitmap();
self.postMessage(resultBitmap, [resultBitmap]);
};