0

I'm using code from this question to make a 'color picker' with colorwheel tool using jQuery UI's draggable function, but I'm having trouble. I can't seem to get the correct location on the canvas image, as my code always returns rgb valeus of 0, 0, 0, no matter where I drag it on the colorwheel. Here's my code:

    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    var canvasWidth = $('#canvas').width();

    function getColor(e) {
        console.log(e);
        var pos = findPos(document.getElementById('currentSelector'));
        console.log(pos)

        x = pos.x;
        y = pos.y;

        var coord = "x=" + x + ", y=" + y;
        var canvasRender = document.getElementById('canvas').getContext('2d');
        var rgba = canvasRender.getImageData(x, y, 1, 1).data;


        var hex = "#" + ("000000" + rgbToHex(rgba[0], rgba[1], rgba[2])).slice(-6);

        var rgb = [];
        for (var i = 0; i < rgba.length - 1; i++){
            var temp = rgba[i];
            rgb[i] = temp;
        };


        console.log(rgb);

        setWorkingColor();

    };


    function findPos(obj) {
        var curleft = 0, curtop = 0;
        if (obj.offsetParent) {
            do {
                curleft += obj.offsetLeft;
                curtop += obj.offsetTop;
            } while (obj = obj.offsetParent);
            return { x: curleft, y: curtop };
        }
        return undefined;
    }

    function rgbToHex(r, g, b) {
        if (r > 255 || g > 255 || b > 255)
            throw "Invalid color component";
        return ((r << 16) | (g << 8) | b).toString(16);
    }

$('.selectors-container').on('drag', '#currentSelector', function(e, ui){
    getColor(e)
});

You can also see a live preview of the problem here: https://adobecolor-shambolaz.c9.io/

Thanks for any help!

EDIT: So the problem with my code was I was passing in the selector element instead of the canvas to the findPos() function, and the x and y variables needed to be changed to the pageX and pageY values of the drag event with respect to the canvas position. Here's the relevant parts of the revised, working code:

function getColor(e) {
    console.log(e);
    var pos = findPos(canvas);
    console.log(pos)
    var x = e.pageX - pos.x;
    var y = e.pageY - pos.y;

    var coord = "x=" + x + ", y=" + y;
    var canvasRender = document.getElementById('canvas').getContext('2d');
    var rgba = canvasRender.getImageData(x, y, 1, 1).data;

    var rgba_data = context.getImageData(x, y, 1, 1).data;
    var rgba = rgba_data;
    console.log(rgba)

    var hex = "#" + ("000000" + rgbToHex(rgba[0], rgba[1], rgba[2])).slice(-6);

    var rgb = [];
    for (var i = 0; i < rgba.length - 1; i++){
        var temp = rgba[i];
        rgb[i] = temp;
    };


    console.log(rgb);

    setWorkingColor();
};

Thanks to markE for the response.

Community
  • 1
  • 1
Ber
  • 695
  • 1
  • 11
  • 17

1 Answers1

2

Simple example of picking colors on a color-wheel:

Hints:

  • Be sure you host the image on the same domain as your web page or else getImageData will not work properly.

  • Get all the pixel color data once at the beginning of your app.

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
  var BB=canvas.getBoundingClientRect();
  offsetX=BB.left;
  offsetY=BB.top;        
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }

var $color=$('#color');
var data,imageWidth;

var colors=new Image;
colors.crossOrigin="anonymous";
colors.onload=function(){
  canvas.width=imageWidth=colors.width;
  canvas.height=colors.height;
  ctx.drawImage(colors,0,0);
  data=ctx.getImageData(0,0,canvas.width,canvas.height).data;
  $("#canvas").mousemove(function(e){handleMouseMove(e);});
}
colors.src="https://dl.dropboxusercontent.com/u/139992952/multple/colorWheel.jpg";


function handleMouseMove(e){
  e.preventDefault();
  e.stopPropagation();
  x=parseInt(e.clientX-offsetX);
  y=parseInt(e.clientY-offsetY);

  var offset=(imageWidth*y+x)*4;
  var red = data[offset];
  var green = data[offset+1];
  var blue = data[offset+2];
  var alpha = data[offset+3];

  $color.text("r:"+red+", g:"+green+", b:"+blue+", a:"+alpha);
}
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4 id="color">RGB under mouse:</h4>    
<canvas id="canvas" width=300 height=300></canvas>
markE
  • 102,905
  • 11
  • 164
  • 176
  • Thanks for the reply, I was able to identify the problem with my code by looking at your example and others - I'll update tomorrow with details. – Ber May 03 '15 at 07:21