SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Hybrid View

  1. #1
    SitePoint Addict
    Join Date
    Nov 2009
    Posts
    312
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Color picker can't read hex code for some colors

    Hi,

    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:

    Code:
    $('#logo').click(function(e) {
    	var canvasOffset = $(canvas).offset();
    	var canvasX = Math.floor(e.pageX - canvasOffset.left);
    	var canvasY = Math.floor(e.pageY - canvasOffset.top);
    	var imageData = ctx.getImageData(canvasX, canvasY, 1, 1);
    	var pixel = imageData.data;
    	var rgbaColor = 'rgba('+pixel[0]+', '+pixel[1]+', '+pixel[2]+', '+pixel[3]+')';
    	var hexColor = pixel[2] + 256 * pixel[1] + 65536 * pixel[0];
    	$('#color-box1').val(rgbaColor);
    	$('#color-box2').val(hexColor.toString(16));
    });
    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.

  2. #2
    SitePoint Addict
    Join Date
    Nov 2009
    Posts
    312
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    SOLVED by inserting another function to handle rgba > hex conversion.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •