-
-
Save ericsoco/3b2674bc2c83a974e352d7b2f18430b6 to your computer and use it in GitHub Desktop.
desaturate canvas image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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