Skip to content

Instantly share code, notes, and snippets.

@andrevenancio
Last active July 5, 2016 01:15
Show Gist options
  • Save andrevenancio/3e3730165b48f341ea1d8c4daf9f2e1d to your computer and use it in GitHub Desktop.
Save andrevenancio/3e3730165b48f341ea1d8c4daf9f2e1d to your computer and use it in GitHub Desktop.
apply a grayscale filter with a pre-build contrast brightness option. (ES6)
grayscale(pixels, contrast, brightness) {
const d = pixels.data;
for (let i = 0; i < d.length; i += 4) {
const r = d[i + 0];
const g = d[i + 1];
const b = d[i + 2];
const a = d[i + 3];
let v = 0.2126 * r + 0.7152 * g + 0.0722 * b;
if (contrast && brightness) {
v /= a;
// Apply contrast.
v = ((v - 0.5) * Math.max(contrast, 0)) + 0.5;
// Apply brightness.
v += brightness;
// Return final pixel color.
v *= a;
}
d[i + 0] = d[i + 1] = d[i + 2] = v;
}
return pixels;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment