Skip to content

Instantly share code, notes, and snippets.

@doctyper
Created May 26, 2011 01:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save doctyper/992342 to your computer and use it in GitHub Desktop.
Save doctyper/992342 to your computer and use it in GitHub Desktop.
desaturate canvas image
// Usage:
// var ctx = canvas.getContext("2d");
// var data = desaturate(ctx);
// ctx.putImageData(data);
var desaturate = function (ctx) {
var imgData = ctx.getImageData(0, 0, dimension, dimension);
for (y = 0; y < dimension; y++) {
for (x = 0; x < dimension; x++) {
i = (y * dimension + x) * 4;
// Apply Monochrome level across all channels:
imgData.data[i] = imgData.data[i + 1] = imgData.data[i + 2] = RGBtoGRAYSCALE(imgData.data[i], imgData.data[i + 1], imgData.data[i + 2]);
}
}
return imgData;
};
var RGBtoGRAYSCALE = function (r, g, b) {
// Returns single monochrome figure:
return window.parseInt((0.2125 * r) + (0.7154 * g) + (0.0721 * b), 10);
};
@loopmode
Copy link

loopmode commented Apr 17, 2020

for a massive performance gain, just omit the back and forth string conversions:

function rgbToGrayscale(r: number, g: number, b: number) {
  // Returns single monochrome figure:
  return 0.2125 * r + 0.7154 * g + 0.0721 * b;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment