如何在mousemove上获取屏幕上像素的颜色?

时间:2021-05-09 13:00:23

标签: javascript jquery

我只想在 jquery 或 javascript 中获得鼠标移动时的像素颜色。有什么可能的方法来获得它,因为我不想使用画布或任何第三方插件。我需要光标位置上那个像素的颜色。

有人帮忙吗?

1 个答案:

答案 0 :(得分:0)

如果您只需要背景颜色,您可以使用 document.elementFromPoint()getComputedStyle()

对于更高级的问题,例如图像中的像素颜色,这将不起作用

window.addEventListener('click', e=>{
  const {clientX:x, clientY:y} = e,
      el = document.elementFromPoint(x, y),
      style = window.getComputedStyle(el);
      
  console.log(style.backgroundColor)
});

initDemo()

function initDemo(){
  const colors =['red','blue', 'purple','green','grey']

  document.querySelectorAll('.box').forEach((el,i)=>{
   el.style.backgroundColor = colors[i]
  });
}
.box{ border:2px solid #ccc; width:50px; margin:30px; height:50px; display:inline-block; color:yellow}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>