日本語

How to Pick a Color from the Screen with an Eyedropper in React

​​React​custom hook,EyeDropper API,Playwright,TypeScript

To pick a color from the screen with an eyedropper, use the browser's EyeDropper API. When a button click calls new EyeDropper().open(), the cursor changes to a magnifier, and when the user clicks a spot, the color of that spot is returned, usually in the form { sRGBHex: "#00c8e8" }. In React, it is easier to manage if you put the picking state and the AbortController for stopping it into a custom hook.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used React 19.3.1, TypeScript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx with tsc and then built for production with esbuild. The eyedropper cannot be operated in a headless browser, so I opened Chromium with a window on a virtual Xvfb screen (1280×800, no window manager) and used xdotool to move the X mouse and send keys to pick colors. I did not test Windows, macOS, Wayland Linux, the stable releases of Google Chrome and Microsoft Edge, multiple or high-DPI screens, or server-side rendering.

At the top are four color swatches labeled sky, peach, grass, and semi-transparent. Below them are a "Pick color with eyedropper" button, a swatch of the picked color, and its color code. When the button is pressed, its label changes to "Picking a color… (Esc to cancel)" and the cursor becomes a magnifier with a checkered pattern. Clicking the sky swatch shows "Picked #00c8e8," and the color code and message turn pink. Next, picking peach gives #d85878. The third time, the eyedropper is opened and the Esc key is pressed, and "Stopped picking the color" appears. A bar at the bottom shows which operation number this is. (The labels in this image are in Japanese. Here, the pink highlight on the changed text, the bar at the bottom, and the click ring were added for the recording.)
Three operations: picking the color of sky, picking the color of peach, and cancelling with Esc. The pink highlight on changed text, the bar at the bottom, and the click ring were added for the recording.

Declare the EyeDropper type

The DOM types in TypeScript 7.0.2, which I used for testing, did not include EyeDropper. If you write new EyeDropper() without a declaration, you get the error Cannot find name 'EyeDropper'. So I declare just the part I need myself.

ts
// TypeScript's DOM types don't include EyeDropper, so declare it ourselves.
interface ColorSelectionResult {
  sRGBHex: string;
}

interface ColorSelectionOptions {
  signal?: AbortSignal;
}

declare class EyeDropper {
  open(options?: ColorSelectionOptions): Promise<ColorSelectionResult>;
}

If you put this in a .d.ts file with no import or export (here src/eyedropper.d.ts), the declaration can be used from any file. I matched the shape to the open() page on MDN. open() accepts an object that has a signal, and it resolves with an object whose sRGBHex holds the chosen color.

Create a hook that opens the eyedropper

ts
import { useCallback, useEffect, useRef, useState } from 'react';

export const isEyeDropperSupported = typeof window !== 'undefined' && 'EyeDropper' in window;

// sRGBHex may return "#rrggbb", but it can also come back in the form "rgba(60, 110, 71, 0)".
// Normalize both to "#rrggbb" (drop the alpha).
export function toHex(value: string): string | null {
  if (/^#[0-9a-f]{6}$/i.test(value)) return value.toLowerCase();
  const m = value.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)/);
  if (!m) return null;
  return '#' + m.slice(1, 4).map((n) => Number(n).toString(16).padStart(2, '0')).join('');
}

export function useEyeDropper() {
  const [picking, setPicking] = useState(false);
  const controllerRef = useRef<AbortController | null>(null);

  // If the component is removed while a color is being picked, close the eyedropper.
  useEffect(() => () => controllerRef.current?.abort(), []);

  // Return the picked color as "#rrggbb". If it's canceled, such as with Esc, return null.
  const pick = useCallback(async (): Promise<string | null> => {
    if (!isEyeDropperSupported || controllerRef.current) return null;
    const controller = new AbortController();
    controllerRef.current = controller;
    setPicking(true);
    try {
      const { sRGBHex } = await new EyeDropper().open({ signal: controller.signal });
      const hex = toHex(sRGBHex);
      if (!hex) throw new Error(`読めない色の形です: ${sRGBHex}`);
      return hex;
    } catch (e) {
      if (e instanceof DOMException && e.name === 'AbortError') return null;
      throw e;
    } finally {
      controllerRef.current = null;
      setPicking(false);
    }
  }, []);

  return { supported: isEyeDropperSupported, picking, pick };
}

pick() returns "#rrggbb" if a color was picked, and null if the user stopped. As described on the open() page on MDN, the Promise fails with AbortError both when the user presses Esc and when the AbortController stops it. Both mean "no color was chosen", so I do not treat them as errors and return null. Any other error is rethrown to the caller.

I keep the AbortController in a ref because it is not a value to show on screen; it only needs to be retrieved when stopping. If abort() is called in the cleanup of useEffect, the eyedropper also closes when the component is removed from the screen while it is open.

A component that shows the picked color

tsx
import { useState } from 'react';
import { useEyeDropper } from './useEyeDropper';

export function ColorDropper() {
  const { supported, picking, pick } = useEyeDropper();
  const [color, setColor] = useState('#ffffff');
  const [history, setHistory] = useState<string[]>([]);
  const [message, setMessage] = useState('');

  async function handleClick() {
    try {
      const hex = await pick();
      if (hex === null) {
        setMessage('色を取るのをやめました');
        return;
      }
      setColor(hex);
      setHistory((prev) => [hex, ...prev.filter((c) => c !== hex)].slice(0, 5));
      setMessage(`${hex} を取りました`);
    } catch (e) {
      setMessage(e instanceof Error ? `色を取れませんでした(${e.message})` : '色を取れませんでした');
    }
  }

  if (!supported) {
    // In browsers that don't support the eyedropper, let the user pick the color with a color input.
    return (
      <label className="dropper">
        色を選ぶ
        <input type="color" value={color} onChange={(e) => setColor(e.target.value)} />
      </label>
    );
  }

  return (
    <div className="dropper">
      <button type="button" onClick={handleClick} disabled={picking}>
        {picking ? '色を選んでいます…(Escでやめる)' : 'スポイトで色を取る'}
      </button>
      <p className="current">
        <span className="swatch" style={{ background: color }} aria-hidden="true" />
        <output>{color}</output>
      </p>
      <p className="message" aria-live="polite">{message}</p>
      {history.length > 0 && (
        <ul className="history" aria-label="取った色">
          {history.map((c) => (
            <li key={c}>
              <span className="swatch" style={{ background: c }} aria-hidden="true" />
              {c}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

The picked colors are kept up to five, with the newest first. If you pick the same color again, it is removed from its old position and moved to the front. In the test environment, I picked the sky, peach, grass, and semi-transparent swatches in that order, then picked sky again. The history became #00c8e8, #ebabbb, #5fae5a, #d85878, and #00c8e8 never appeared twice in the list.

While the eyedropper is open, the button is disabled and its label changes to "Picking a color… (Esc to cancel)" (the label text is in the code above). As described in the EyeDropper API page on MDN, while the eyedropper is active, clicking anywhere on the screen picks a color. The only way for the user to cancel is the Esc key, so the button label tells them that.

The eyedropper can only be opened right after a click

As described on the EyeDropper API page on MDN, open() can only be called in response to a user action such as a button click. This keeps sites from reading colors on the screen without the user knowing. In the test environment, I tried calling it at different times, with these results:

When open() was called Result
Right after the page opened (no interaction) NotAllowedError
100 ms after a click The eyedropper opened
6 seconds after a click NotAllowedError

The message at the end of NotAllowedError was EyeDropper::open() requires user gesture. in both failing cases. For a while after a click, the page counts as having just been acted on (MDN's glossary calls this transient activation). The HTML specification says this state lasts "at most a few seconds." If, inside a click handler, you await the end of some other process before calling open(), a long wait fails in the same way as the 6-second case in the table above. Call open() first in the handler.

Two ways to stop it: Esc and AbortController

If you press the Esc key after the eyedropper opens, open() fails with AbortError, and the message at the end was The user canceled the selection. The hook turns this into null, so the screen shows "Stopped picking the color."

To stop it from code, call abort() on the AbortController that was passed as signal to open(). In the test environment, this failed with AbortError, and the message was signal is aborted without reason. The hook's cleanup does this. When the component is removed while the eyedropper is open, abort() is called. After that, clicking the peach swatch did not pick its color; the click was treated as an ordinary click on the page.

If you call open() again while it is already open, it fails with InvalidStateError, and the message at the end was EyeDropper is already open. The hook returns null without calling open() when controllerRef.current is set, and it also disables the button so that a second call cannot be made.

Only the colors visible on screen can be picked

The eyedropper reads the color of the point displayed on the screen, not the CSS value of an element. The EyeDropper API page on MDN also says that colors on the screen can be picked, including outside the browser window.

In the test environment, when I picked the semi-transparent swatch, which is #d85878 at 50% opacity over a white background, the result was #ebabbb. That is #d85878 and white mixed half and half. The returned color is the one seen after overlapping with white, not the #d85878 specified in CSS.

I also tested outside the window. I set the Xvfb screen background to #3c6e47 with xsetroot, and clicked the background to the right of a 640px-wide window (x=740, y=300). It returned #3c6e47.

When I clicked with the eyedropper, the click event on the element underneath did not fire. I added onClick to the swatch and counted; after four eyedropper clicks, the count was still 0.

The value can come back in rgba() form

The open() page on MDN says sRGBHex takes the form #aabbcc. However, when I picked the background outside the window in the test environment, sRGBHex was "rgba(60, 110, 71, 0)" as is. When I picked the sky swatch inside the page using the same steps, it was "#00c8e8".

In the Chromium source, the picked color is turned into a string with SerializeAsCanvasColor(). In the test environment, I set a color in a canvas fillStyle and read it back: an opaque color came back as #3c6e47, and passing rgba(60, 110, 71, 0) returned that same form unchanged, matching what the eyedropper returned. The point outside the window came back as a color with alpha 0, which is why it is in rgba() form.

The hook's toHex() accepts this form too and normalizes it to #rrggbb. It drops the alpha and uses only the red, green, and blue values. In the test environment, rgba(60, 110, 71, 0) became #3c6e47, which matched the color I had painted on the screen background. If a value comes back in neither form, null is returned and the hook rethrows it as an error.

Point

If you pass sRGBHex to something like <input type="color">'s value, first check that it is in the #rrggbb form.

In browsers without support, show a color input

According to the browser compatibility data on MDN, the EyeDropper API has been available since Chrome 95, and desktop Edge and Opera are the same. Firefox, Safari, and Chrome on Android do not support it. On Linux, it works with X11 but not with Wayland.

So check first whether it is available with 'EyeDropper' in window. The EyeDropper API can only be used on secure pages such as those served over HTTPS (secure contexts) (see the EyeDropper page on MDN). In the test environment, on a http://localhost page, isSecureContext was true and EyeDropper was present. On an about:blank page opened with Playwright's setContent(), isSecureContext was false and EyeDropper was not present.

When it is not available, ColorDropper shows an <input type="color"> in place of the eyedropper button. In headless Chromium, I removed window.EyeDropper before the page was displayed. The eyedropper button did not appear, and one color input with a "Choose a color" label was shown. When I set its value to #5fae5a, the input's value also became #5fae5a. For more on handling color inputs, see my earlier article "How to Create a Color Picker Input in React."

​Posted by 86