Skip to content

Instantly share code, notes, and snippets.

@ericsoco
Forked from doctyper/desaturate.js
Last active February 9, 2017 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericsoco/3b2674bc2c83a974e352d7b2f18430b6 to your computer and use it in GitHub Desktop.
Save ericsoco/3b2674bc2c83a974e352d7b2f18430b6 to your computer and use it in GitHub Desktop.
desaturate canvas image
// Usage:
// let ctx = canvas.getContext("2d");
// let data = desaturate(0.5, ctx, canvas.width, canvas.height);
// ctx.putImageData(data);
function desaturate (amount, ctx, w, h) {
let imgData = ctx.getImageData(0, 0, w, h),
x, y, i,
grey;
for (y = 0; y < h; y++) {
for (x = 0; x < w; x++) {
i = (y * w + x) * 4;
grey = window.parseInt(0.2125 * imgData.data[i] + 0.7154 * imgData.data[i + 1] + 0.0721 * imgData.data[i + 2], 10);
imgData.data[i] += amount * (grey - imgData.data[i]);
imgData.data[i + 1] += amount * (grey - imgData.data[i + 1]);
imgData.data[i + 2] += amount * (grey - imgData.data[i + 2]);
}
}
return imgData;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment