Creating Image Negative Using HTML5

In this article we learn how to create a negative of an image using HTML5. When the user clicks on the button, the image is inverted to a negative and when the user clicks again, the image is inverted back to original.

Step 1 : First we define a body for the HTML using the canvas element and a button, like this:

<body><div><h1>Creating Image Negative</h1><inputid='Neg_Button'type='button'value="Negative"onclick="return Neg_Button_onclick()"/></div><canvasid='canvas'width='800'height='750'>Sorry,Canvas is not supported in this Browser..</canvas><scriptsrc='negative_script.js'></script></body>

Step 2 : Then we define JavaScript to add functionality in our HTML page. We use the getElementById method to get the canvas and button id and the Canvas.getContext('2d') method returns an object that provides methods and properties for drawing and image manipulations on the canvas element, like this:var canvas = document.getElementById('canvas'),context = canvas.getContext('2d'),image = new Image(),Neg_Button = document.getElementById('Neg_Button'); ;image.src = 'bridge.jpg';

Step 3 : Now we define a function in JavaScript. The Neg_Button_onclick function is used to set the red, green and blue values of each pixel to 255 minus the current value so that setting inverts the colors. The getImageData method gives you access to pixels of an image and the setImageData method is used to put pixels back in the image, like this:function Neg_Button_onclick() {var idata = context.getImageData(0, 0, canvas.width, canvas.height), data = idata.data;for (i = 0; i <= data.length - 4; i += 4) { data[i] = 255 - data[i] data[i + 1] = 255 - data[i + 1]; data[i + 2] = 255 - data[i + 2]; } context.putImageData(idata, 0, 0);}

Step 4 : We use CSS in the Head section for describing the the look and formatting to our HTML page, like this: