0

I am having a requirement to get color hex code of any point in the current page of my application on mouse click. I searched on the web and came across one post

https://stackoverflow.com/questions/7690331/get-hex-value-of-clicked-on-color-with-jquery

I tried with the reference links in the post

https://developer.mozilla.org/en-US/docs/Archive/Add-ons/Code_snippets/Canvas

but I cannot even get the returned rgb values when cliked.The rgb values always returned were

{r: 0, g: 0, b: 0, a: 0}

My code is given below

JS Code

var canvas = $("<canvas>"); //Create the canvas element

//Create a layer which overlaps the whole window
canvas.css({position:"fixed", top:"0", left:"0",
            width:"100%", height:"100%", "z-index":9001});

canvas.click(function(ev){
 var x = ev.pageX;
 var y = ev.pageY;
 console.log(x);
 console.log(getpixelcolour(this, x, y));
});
canvas.appendTo("body:first"); 

function getpixelcolour(canvas, x, y) {
  var cx = canvas.getContext('2d');
  var pixel = cx.getImageData(x, y, 1, 1);  
  return {
    r: pixel.data[0],
    g: pixel.data[1],
    b: pixel.data[2],
    a: pixel.data[3]
  };
}

HTML code

<htmL>
<body style="background-color:yellow">
<div style="background-color:red">
Red
</div>
<div style="background-color:green">
green
</div>
<div style="background-color:blue">
blue
</div>
</body>
</htmL>

My efforts are also put in the JS Fiddle link

https://jsfiddle.net/ha49gjdt/19/

Can anyone suggest me what could have I done wrong.

0 Answers0