EyeDropper 拾色器

EyeDropper

EyeDropper:拾色器,从屏幕上选择颜色
需要用户交互操作


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>EyeDropper</title>
  </head>
  <body>
    <strong>EyeDropper</strong>
    <hr />
    <button type="button" id="btn-open">打开 EyeDropper, 选择颜色</button>
    <div>
      <span>当前选择的颜色:</span>
      <input type="color" id="color-input" value="#ffffff" />
      <b id="result"></b>
    </div>

    <script>
      // EyeDropper: 从屏幕上选择颜色
      // 该 API 不允许在没有用户意图的情况下启动拾色器模式。只能在用户操作(例如按钮点击)的响应中调用 EyeDropper.prototype.open() 方法

      const openBtn = document.getElementById('btn-open');
      const result = document.getElementById('result');
      const colorInput = document.getElementById('color-input');

      let eyeDropper = null;
      openBtn.addEventListener('click', async () => {
        if (!eyeDropper) {
          eyeDropper = new EyeDropper();
        }

        try {
          // 打开 EyeDropper 选择颜色
          const { sRGBHex } = await eyeDropper?.open();
          console.log('color => ', sRGBHex);
          result.textContent = sRGBHex;
          colorInput.value = sRGBHex;
        } catch (error) {
          const { message } = new Error(error);
          if (message.includes('canceled')) {
            // 用户取消选择颜色
            console.log('已取消选择颜色');
          } else {
            console.log('error => ', message);
          }
        }
      });
    </script>
  </body>
</html>
posted @ 2024-04-29 21:53  _clai  阅读(43)  评论(0编辑  收藏  举报