Now we're going to grayscale Obama. To do this we average out the r, g, b values of each pixel, then assign that average back to each color.
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var imgData;
var img = new Image();
img.src = "/img/obama.png";
img.onload = function handleLoad() {
ctx.drawImage(0, 0, img.width. img.height);
imgData = ctx.fetchImage(0, 0, img.width, img.height);
//make obama gray
handleData();
//draw gray obama back to canvas
ctx.putImageData(imgData, 0, 0);
}
function handleData() {
var i,
d = imgData.data,
leng = d.length,
//declare variable to hold avg
avg;
for (i = 0 ; i < leng ; i+=4) {
//caculate avg
avg = (d[i] + d[i+1] + d[i+2])/3;
//assign avg to each color
//we can leave the alpha value alone
d[i] = avg;
d[i+1] = avg;
d[i+2] = avg;
}
}
Nice, yes we can make Obama gray.
Or we can make Obama trippy by inverting him. To do this we assign the result of subtracting each color from 255:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var imgData;
var img = new Image();
img.src = "/img/obama.png";
img.onload = function handleLoad() {
ctx.drawImage(0, 0, img.width. img.height);
imgData = ctx.fetchImage(0, 0, img.width, img.height);
//make obama alien
handleData();
//draw alien obama back to canvas
ctx.putImageData(imgData, 0, 0);
}
function handleData() {
var i,
d = imgData.data,
leng = d.length,
//declare variable to hold avg
avg;
for (i = 0 ; i < leng ; i+=4) {
//invert each color
d[i] = 255 - d[i];
d[i+1] = 255 - d[i+1];
d[i+2] = 255 - d[i+2];
}
}
There is so much you can do with image data, these are just two examples.