我需要在鼠标单击时获取应用程序当前页面中任何点的颜色十六进制代码。我在网上搜索并发现了一个帖子
https://stackoverflow.com/questions/7690331/get-hex-value-of-clicked-on-color-with-jquery
我尝试了帖子中的参考链接
https://developer.mozilla.org/en-US/docs/Archive/Add-ons/Code_snippets/Canvas
但是在cliked时我甚至无法获得返回的rgb值。总是返回的rgb值是
{r: 0, g: 0, b: 0, a: 0}
我的代码如下:
JS代码
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代码
<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>
我的努力也放在了JS Fiddle链接
https://jsfiddle.net/ha49gjdt/19/
任何人都可以建议我做错了什么。