EyeDropper 拾色器

_clai發表於2024-04-29

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>

相關文章