Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions demos/workers/modules/filters.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export function none() {}

export function grayscale({ data: d }) {
for (let i = 0; i < d.length; i += 4) {
const [r, g, b] = [d[i], d[i + 1], d[i + 2]];

// CIE luminance for the RGB
// The human eye is bad at seeing red and blue, so we de-emphasize them.
d[i] = d[i + 1] = d[i + 2] = 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
};

export function brighten({ data: d }) {
for (let i = 0; i < d.length; ++i) {
d[i] *= 1.2;
}
};
64 changes: 64 additions & 0 deletions demos/workers/modules/page.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<!DOCTYPE html>
<meta charset="utf-8">
<title>Worker example: image decoding</title>

<label>
Type an image URL to decode
<input type="url" id="image-url" list="image-list">
<datalist id="image-list">
<option value="https://html.spec.whatwg.org/images/drawImage.png">
<option value="https://html.spec.whatwg.org/images/robots.jpeg">
<option value="https://html.spec.whatwg.org/images/arcTo2.png">
</datalist>
</label>

<label>
Choose a filter to apply
<select id="filter">
<option value="none">none</option>
<option value="grayscale">grayscale</option>
<option value="brighten">brighten by 20%</option>
</select>
</label>

<script type="module">
const worker = new Worker("worker.js", { type: "module" });
worker.onmessage = receiveFromWorker;

const url = document.querySelector("#image-url");
const filter = document.querySelector("#filter");
const output = document.querySelector("#output");

url.oninput = updateImage;
filter.oninput = sendToWorker;

let imageData, context;

function updateImage() {
const img = new Image();
img.src = url.value;

img.onload = () => {
output.innerHTML = "";

const canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;

context = canvas.getContext("2d");
context.drawImage(img, 0, 0);
imageData = context.getImageData(0, 0, canvas.width, canvas.height);

sendToWorker();
output.appendChild(canvas);
};
}

function sendToWorker() {
worker.postMessage({ imageData, filter: filter.value });
}

function receiveFromWorker(e) {
context.putImageData(e.data, 0, 0);
}
</script>
7 changes: 7 additions & 0 deletions demos/workers/modules/worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import * as filters from "./filters.js";

self.onmessage = e => {
const { imageData, filter } = e.data;
filters[filter](imageData);
self.postMessage(imageData, [imageData.data.buffer]);
};
Loading