Skip to content

Instantly share code, notes, and snippets.

@zazaulola
Created July 20, 2024 05:37
Show Gist options
  • Save zazaulola/f82029a70d09c870f25bc6efde115a6f to your computer and use it in GitHub Desktop.
Save zazaulola/f82029a70d09c870f25bc6efde115a6f to your computer and use it in GitHub Desktop.
Grayscale image halftone dithering
onmessage = ({ data: { data, width, height } }) => {
const thresholdMap = [
[15, 135, 45, 165],
[195, 75, 225, 105],
[60, 180, 30, 150],
[240, 120, 210, 90],
];
let min = 255,
max = 0,
avg = 0,
cnt = 0;
for (let i = 0; i < data.length; i += 4) {
[min, max] = [Math.min(min, data[i]), Math.max(max, data[i])];
avg += (data[i] - avg) / ++cnt;
}
const threshold = Math.floor((min + max + 2 * avg + 384) / 8);
let i = 0;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++, i += 4) {
const newPixel = Math.floor((data[i] + thresholdMap[x % 4][y % 4]) / 2) > threshold ? 255 : 0;
data[i + 0] = newPixel;
data[i + 1] = newPixel;
data[i + 2] = newPixel;
}
}
postMessage(data);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment