Invert image using the HTML5 canvas

Why does HTML 5 attract web developers

In HTML5 canvas’s 2D context support three methods that can draw pixel by pixel: createImageData, getImageData, and putImageData. With the help of these methods you can filtering the image on the canvas such as inversion of the image. The following code section will show you that how can you invert the image on canvas.

The below figure is the screenshots of the original image and its invert image:

Invert image in html5

Full Code:

<html>
<head>
    <title>Load image in HTML5 Canvas</title>
<style>
#maindiv canvas{border:1px solid #bbb;}
</style>
    <script type="text/javascript">
        var  ctx1;
 function init() {
     can1 = document.getElementById("MyCanvas1");
     ctx1 = can1.getContext("2d");
	 var img = new Image(); 
	 img.src = 'html5.jpg';
     img.onload = function() {
        can1.width = img.width +20;
        can1.height = img.height +20;
		ctx1.drawImage(img,0,0);
		var imageData = ctx1.getImageData(0, 0, img.width, img.height);
        var data = imageData.data;
        for(var 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
        }
        ctx1.putImageData(imageData,img.width + 20, 0);
  }
 }
    </script>
</head>
<body onload="init();">
<div id="maindiv">
    <canvas id="MyCanvas1" width="600" height="200">
  This browser or document mode doesn't support canvas object</canvas>
  </div>
</body>
</html>

From the above you can see that we are calculating the new value of the red, green and blue values of all the pixels in the image(by subtracting original value from the max value 255). And then we are redrawing the image with this imageData object using the putImageData() method. You can say it as Pixel-based manipulation of the canvas, this helps to do more on the filtering of image.