Book
Image manipulation
Image manipulation
Completion requirements
View
- Manipulate the colors
Inverse color
Now we will iterate over the bitmap array pix and we will inverse the color of prototype.png. After this, we will put the new image data into the canvas2:
This JavaScript code for the above is:
/* Loop over each pixel and invert the color.*/
for (var i = 0, n = pix.length; i < n; i += 4) {
imgData2.data[i ] = 255 - pix[i ]; /* red */
imgData2.data[i+1] = 255 - pix[i+1]; /* green */
imgData2.data[i+2] = 255 - pix[i+2]; /* blue */
imgData2.data[i+3] = pix[i+3]; /* alpha */
}
console.log(imgData2);
/* now draw the new image data on the second canvas */
context2.putImageData(imgData2, 0, 0);
this will create the following image:
Important Note: To do this exercise using your local file system, you will need to use Firefox as your browser. Chrome will display an error due to security constraints.