javascript - 使用 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/
谁能建议我我做错了什么。
解决方案
推荐阅读
- c++ - Bad instanition in function that is not itself instantiated. Difference in behaviour between clang and gcc
- qnamaker - QnA Maker Web 应用程序 - 如果未找到结果,则调用 REST API
- spring-boot - 出现错误配置的节点都不可用:在弹性搜索中
- python - 使用 Google 表格触发位于 Google Drive 中的 Python 脚本
- java - C++ 客户端向 Java 服务器发送奇怪的数据
- python - Django中正确的身份验证测试结构
- javascript - Google Cloud Function 不会触发 Stripe 的端点
- python - 如何在数据框中列出路径时使用 pyspark 读取镶木地板文件
- spring-boot - 访问注解中的方法签名变量
- javascript - webpack 生成带有哈希的文件并将其包含在应用程序的某个位置