HTML5 : Canvas pixels

Once we know we can do an image drawing in a canvas, lets see if we can at all make a new image from a blank canvas. The answer is yes. We have absolutely accessible to each pixel values of the context of the Canvas.

Let me say you here, if you are not getting the result in one browser, try other browsers. I had tried a long time with the same code in Chrome without any result! But it worked out in latest version of Opera !! Not sure whats wrong but if you test it in other browsers it will save you a lot of time.

The code for image creation is as below.

createImage=function()
	{
		// Create an ImageData object.
		var imgd = context_one.createImageData(width,height);
		var pix = imgd.data;
		// Loop over each pixel and set a transparent red.
		for (var i = 0; n = pix.length, i < n; i += 4) {
		  pix[i  ] = 255; // red channel
		  pix[i +1] = 0; // green channel
		  pix[i +2] = 0; // blue channel
		  pix[i+3] = 255; // alpha channel
		}
		// Draw the ImageData object at the given (x,y) coordinates.
		context_one.putImageData(imgd, 0,0);
	}

All we have to do is create an image data with a width and height, that is done as

var imgd = context_one.createImageData(width,height);

The above code, I have taken the width as canvas width and height as canvas height.
Now we will access each element of that image data array. Since its just an array the pixel values of each pixel is stored linearly as "red,green,blue,alpha" and so we have to loop over each 4th element and get the values of all the channels of each pixel. Thats exactly what our for loop is doing. Then we are only populating the red channel to its max, since we want a red fill canvas image :) !
Lastly the image data must be put on the context so as to render the pixels. The following code does that.

context_one.putImageData(imgd, 0,0);

Thats a simple pixel manipulation we did now with our canvas element.
The source code is available here for you to download and play.