EyeDropper 实现拾色器(滴管取色)功能

前面讲到使用dom-image + canvas 实现滴管取色功能  , 这个方式最大的有点就是兼容性高,适配大多数的浏览器,但是也有不足的地方:

  • 图片的生成是需要时间的,所以在图片生成之前如果耗时过长就会有卡顿问题
  • 只能拾取到当前浏览器页面的颜色,超出浏览器标签页外的颜色就无法拾取

不过还有一个解决方案,谷歌浏览器推出了一个原生拾色器API(目前只有谷歌和Edge支持), 功能强大到可以拾取电脑桌面的颜色【算是浏览器级别插件了,其他浏览器估计还要再等等】

https://developer.mozilla.org/zh-CN/docs/Web/API/EyeDropper

运行截图:

具体用法也很简单,demo代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>EyeDropper API</title>
  <style>
    body {
      background: #f5deb3;
      display: grid;
      place-content: center;
      place-items: center;
      height: 100vh;
      margin: 0;
      transition: background-color .2s ease-out;
    }
    #partySmiley {
      margin: 50px;
      width: 250px;
      filter: drop-shadow(0px 10px 20px #333);
    }
    #eyedroppingTime {
      width: max-content;
      font-size: 18px;
      font-weight: bold;
      border-radius: 5px;
      padding: 5px;
      background-color: #EEE;
      border: 4px solid #333;
      margin-bottom: 20px;
    }
    #eyedroppingTime:hover {
      background-color: #FFF;
    }
    #warning {
      display: none;
      font-family: sans-serif;
      font-size: 16px;
      padding: 10px;
      border-radius: 5px;
      background-color: rgb(255 255 255 / 50%);
    }
    #warning span {
      font-weight: bold;
    }
  </style>
</head>
<body>
  <img id="partySmiley" src="https://www.kirupa.com/icon/1f973.svg">
  <button id="eyedroppingTime">🎨 Pick a Color</button>
  <p id="warning">Your browser doesn't support the <span>EyeDropper API</span>!</p>

  <script>
    let eyedropperButton = document.querySelector("#eyedroppingTime");
    let warningElement = document.querySelector("#warning");

    function setup() {
      if (window.EyeDropper === undefined) {
        eyedropperButton.style.display = "none";
        warningElement.style.display = "block";
        return;
      } else {
        eyedropperButton.addEventListener("click", pickColor, false);
      }
    }
    setup();

    async function pickColor(event) {
      let eyeDropper = new EyeDropper();

      try {
        let pickedColor = await eyeDropper.open();

        document.body.style.background = pickedColor.sRGBHex;
        warningElement.style.display = "none";
      } catch (error) {
        warningElement.style.display = "block";
        warningElement.innerText = error;
      }
    }
  </script>
</body>
</html>

兼容性表格:

最后,综合EyeDroper和dom-image,可以结合二者做一个比较好的拾色器优化方案:

谷歌浏览器上使用eyeDroper, 在其他浏览器上采用dom-image + canvas实现拾色器方案

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值