首页 > 解决方案 > 使用 Jquery 选择鼠标点击点的颜色十六进制代码

问题描述

我需要在鼠标单击时获取应用程序当前页面中任何点的颜色十六进制代码。我在网上搜索并发现了一个帖子

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

但我什至无法在单击时获得返回的 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/

谁能建议我我做错了什么。

标签: javascriptjquerycanvas

解决方案


推荐阅读