Invert image colors (create negative) in html5 canvas using JavaScript.

Converting an image to its digital negative is very easy using JavaScript. We can achieve it in three steps.

  1. Access individual color value of each pixel in the image.
  2. Subtract color value from 255 to obtain its complimentary color value.
  3. Put the new complimentary color values back into the pixels.

 

Learn the basics of loading an image into canvas and manipulate its pixels here.

Download the full source code and image at the end of this page.

 

The code:

var imageData = context.getImageData(imageX, imageY, image.width, image.height);
var dataArr = imageData.data;

for(var i = 0; i < dataArr.length; i += 4)
{
    var r = dataArr[i]; // Red color lies between 0 and 255
    var g = dataArr[i + 1]; // Green color lies between 0 and 255
    var b = dataArr[i + 2]; // Blue color lies between 0 and 255
    var a = dataArr[i + 3]; // Transparency lies between 0 and 255

    var invertedRed = 255 - r;
    var invertedGreen = 255 - g;
    var invertedBlue = 255 - b;

    dataArr[i] = invertedRed;
    dataArr[i + 1] = invertedGreen;
    dataArr[i + 2] = invertedBlue;
}
        
context.putImageData(imageData, imageX, imageY);

 

Original image:

sydney harbour bridge

 

Image converted to its digital negative:

sydney harbour bridge with colors inverted

McAfee APAC


You might want to contribute to Qoncious.com:




Latest Videos