Canvas How to - Invert an image








Question

We would like to know how to invert an image.

Answer


<!--   w  w w.  j a  v a 2s. c  o  m-->
<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {  
        var canvas = $("#myCanvas");
        var context = canvas.get(0).getContext("2d");
        
        // Inverting
        var image = new Image();
        image.src = "http://www.java2s.com/style/download.png";
        $(image).load(function() {
          context.drawImage(image, 0, 0, 1024, 683, 0, 0, 500, 500);
          
          var imageData = context.getImageData(0, 0, canvas.width(), canvas.height());
          var pixels = imageData.data;
          var numPixels = pixels.length;
          
          // Clear the image
          context.clearRect(0, 0, canvas.width(), canvas.height());
        
          // Access and change pixel values
          for (var i = 0; i < numPixels; i++) {
            pixels[i*4] = 255-pixels[i*4]; // Red
            pixels[i*4+1] = 255-pixels[i*4+1]; // Green
            pixels[i*4+2] = 255-pixels[i*4+2]; // Blue
          };
          
          // Draw image data to the canvas
          context.putImageData(imageData, 0, 0);
        });

      });
    </script>
  </head>
  <body>
    <canvas id="myCanvas" width="500" height="500">
      <!-- Insert fallback content here -->
    </canvas>
  </body>
</html>

The code above is rendered as follows: