The following code inverts the colors of an image by inverting the color of each pixel.
This recipe must be run on a web server due to security constraints with the getImageData() method.
<!DOCTYPE HTML> <html> <head> <script> window.onload = function(){ let canvas = document.getElementById("myCanvas"); let context = canvas.getContext("2d"); //from w ww. ja va 2 s . c o m let imageObj = new Image(); imageObj.onload = function(){ let sourceWidth = this.width; let sourceHeight = this.height; let sourceX = canvas.width / 2 - sourceWidth / 2; let sourceY = canvas.height / 2 - sourceHeight / 2; let destX = sourceX; let destY = sourceY; context.drawImage(this, destX, destY); let imageData = context.getImageData(sourceX, sourceY, sourceWidth, sourceHeight); let data = imageData.data; for (let i = 0; i < data.length; i += 4) { data[i] = 255 - data[i]; // red data[i + 1] = 255 - data[i + 1]; // green data[i + 2] = 255 - data[i + 2]; // blue // i+3 is alpha (the fourth element) } context.putImageData(imageData, destX, destY); }; imageObj.src = "http://java2s.com/style/download.png"; }; </script> </head> <body> <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;"> </canvas> </body> </html>
To invert the color of an image using HTML5 canvas, loop through all of the pixels in an image and invert each pixel using a color inverting algorithm.
To invert a pixel's color, we can invert each of its RGB components by subtracting each value from 255 as follows:
data[i ] = 255 - data[i ]; // red data[i+1] = 255 - data[i+1]; // green data[i+2] = 255 - data[i+2]; // blue
Once the pixels are updated, redraw the image using the putImageData() method of the canvas context:
context.putImageData(imageData, destX, destY);
This method can draw an image using image data instead of a source image with the drawImage() method.