DEV Community

Cover image for Introducing the EyeDropper API
Mads Stoumann
Mads Stoumann

Posted on

Introducing the EyeDropper API

The EyeDropper API has landed in Chrome 95. This API opens up a lot of possiblities. A user can select colors from images, create her/his own color-theme, and much more.

Let's built a simple, ultra-small ColorPicker, using this new API.

First, we need a form with a large selection-area, a hue-slider, and an output:

<form class="picker" id="app">
  <fieldset class="background" name="background">
    <div class="brightness"></div>
    <div class="saturation"></div>
  </fieldset>
  <label aria-label="hue">
    <input type="range" name="hue" max="360" value="0" data-blok="range">
  </label>
  <output name="hex" data-value="#ff0000"></output>
</form>
Enter fullscreen mode Exit fullscreen mode

The selection-area consists of a background with the main color, as well as saturation and lightness layers, which are gradients on top of that color:

Background with saturation and lightness

The hue-slider is a regular <input type="range">, styled with 12 color-stops (360 degrees / 12 = a stop every 30 degree):

Hue-slider

To update the hue as we drag the hue-slider, we need a bit of JavaScript, updating a simple custom property, --hue:

app.elements.hue.addEventListener('input', () => app.style.setProperty('--hue', app.elements.hue.valueAsNumber));
Enter fullscreen mode Exit fullscreen mode

Next, if the EyeDropper API is supported in the browser (currently only Chrome 95+), we'll add a click-listener to the selection-area:

if ('EyeDropper' in window) {
app.elements.background.addEventListener('click', pickColor)
}
Enter fullscreen mode Exit fullscreen mode

And finally, we'll invoke the EyeDropper API with the pickColor-function:

async function pickColor() {
  const ED = new EyeDropper();
  const result = await ED.open();
  app.style.setProperty('--hex', result.sRGBHex);
  app.elements.hex.dataset.value = result.sRGBHex;
}
Enter fullscreen mode Exit fullscreen mode

Now, try it out:

EyeDropper

And that's it! A ColorPicker with approx 200 bytes of JavaScript, when minified and gzipped.

In a real-life scenario, you'd probably add a “selection”-circle, listen for pointer-move-events etc., but this should get you started.

Here's a Codepen-demo:

Discussion (0)