Skip to content

Instantly share code, notes, and snippets.

@leemartin
Created February 21, 2022 18:00
Show Gist options
  • Save leemartin/367fc5d0441ab5591af4ed9842e89513 to your computer and use it in GitHub Desktop.
Save leemartin/367fc5d0441ab5591af4ed9842e89513 to your computer and use it in GitHub Desktop.
Desaturate Canvas
let desaturate = (canvas) => {
// Get canvas image data
let imageData = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height)
// Get all pixels
let pixels = imageData.data
// Loop through pixels
for (let i = 0; i < pixels.length; i += 4) {
// Adjust lightness
let lightness = parseInt((pixels[i] + pixels[i + 1] + pixels[i + 2])/3)
pixels[i] = lightness
pixels[i + 1] = lightness
pixels[i + 2] = lightness
}
}
// Update image data
canvas.getContext('2d').putImageData(imageData, 0, 0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment