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>
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:
The hue-slider is a regular <input type="range">
, styled with 12 color-stops (360 degrees / 12 = a stop every 30 degree):
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));
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)
}
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;
}
Now, try it out:
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:
Top comments (0)