Color picker can't read hex code for some colors


I am working on a jQuery color picker and I have the following code to display the rgba and hex values of the pixel that is clicked by the mouse:

$('#logo').click(function(e) {
	var canvasOffset = $(canvas).offset();
	var canvasX = Math.floor(e.pageX - canvasOffset.left);
	var canvasY = Math.floor(e.pageY -;
	var imageData = ctx.getImageData(canvasX, canvasY, 1, 1);
	var pixel =;
	var rgbaColor = 'rgba('+pixel[0]+', '+pixel[1]+', '+pixel[2]+', '+pixel[3]+')';
	var hexColor = pixel[2] + 256 * pixel[1] + 65536 * pixel[0];

The above code gets and displays rgba value correctly but it fails to get the correct value for hex code on some pixels. For example, for some pixels it returns the correct hex value but for some other pixels it returns a 4 or 5 digit hex code value and for black it returns “0”. Is something wrong with my hex code (hexColor) calculation above?

Thanks for your help.

SOLVED by inserting another function to handle rgba > hex conversion.