使用JS如何检测我正在盘旋的颜色?

问题描述 投票:0回答:1

我正在使用反应,我有这个代码,当我悬停时准确检测背景颜色,但当使用渐变时,它回复整个"linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet)"。有没有办法我可以检测到任何颜色,就像使用js的开发工具一样?

  const getColor = (div, e) => {
    console.log(div, e, e.target, window.getComputedStyle(e.target).getPropertyValue("backgroundImage"))
    let color = window.getComputedStyle(e.target).getPropertyValue("background-color"); 
    //let color = window.getComputedStyle(e).getPropertyValue("background-color")
    //console.log(color)
    setTheme(color)
  }

  return (
    <div className="row">
      <div className="col-md-12">
        <div className="row">
          <div className="col-md-12" onMouseOver={(e) => getColor(this,e)}>
            <br />
            <div style={{backgroundImage: "linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet)"}}>Blue</div>
            <div style={{backgroundColor:"red"}}>Red</div>
            <div style={{backgroundColor:"yelllow"}}>Yellow</div>
            .......
javascript reactjs colors mouseover
1个回答
1
投票

JavaScript没有关于常规html节点的此类信息(除非浏览器扩展是一个选项)。您可以使用画布完成所需的操作,您可以在其中处理每个像素。

看看这个片段:http://jsfiddle.net/89wLbh3q/14/

$('#example').mousemove(function(e) {
    var pos = findPos(this);
    var x = e.pageX - pos.x;
    var y = e.pageY - pos.y;
    var coord = "x=" + x + ", y=" + y;
    var c = this.getContext('2d');
    var p = c.getImageData(x, y, 1, 1).data; 
    var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
    $('#status').html(coord + "<br>" + hex);
});

如果canvas不是选项,请尝试在隐藏的画布中渲染CSS渐变。您还可以使用html2canvas.将html转换为隐藏的画布

© www.soinside.com 2019 - 2024. All rights reserved.