Add a color picker to your web app with the EyeDropper API
Harrison Grieve on May 20, 2022
For developers who want a simple way to add color picking functionality to their apps, it may soon be possible with the help of the EyeDropper API. This experimental Web API allows you to capture the color value of a single pixel - not just in the browser window, but anywhere on your screen!
Using the EyeDropper API
The EyeDropper API exposes an EyeDropper
window object with a single asynchronous method: EyeDropper.open()
Checking for compatibility
Especially because it is an experimental feature, it is important to check for compatibility before using the EyeDropper API. Â
// index.js
// Check for EyeDropper compatibility
if ("EyeDropper" in window) {
// EyeDropper logic goes here...
}
Instantiating the EyeDropper object
Once we have established compatibility, we can instantiate a new EyeDropper object.
// index.js
// Check for EyeDropper compatibility
if ("EyeDropper" in window) {
const dropper = new EyeDropper()
}
Adding a trigger element
One interesting aspect of the EyeDropper API is that it requires user intent to open, such as a click event. This is done to prevent pixel data from being revealed without the user's knowledge or consent.
Let's add a button that the user can click to open the color picker.
<!-- index.html -->
<button id="colorPickerTrigger">Open Color Picker</button>
Opening the EyeDropper on user input
In order to successfully open the eyedropper, we need to take the following steps:
- Register an event listener to the trigger element
- Inside the callback, invoke the
EyeDropper.open()
method - Handle the
Promise
returned byEyeDropper.open()
The promise will resolve to an object with a single property sRGBHex
containing the hex color value (i.e #91db99
)
The promise will reject if the user presses <ESC>
while the color picker is open or if an AbortSignal
(passed to the options
object) abort()
is called while the color picker is open.
// index.js
// Check for EyeDropper compatibility
if ("EyeDropper" in window) {
// instantiate the eyedropper object
const dropper = new EyeDropper()
trigger.addEventListener('click', (_e) => {
dropper.open()
.then(result => {
console.log(result.sRGBHex);
})
.catch(err => {
console.warn('Color picker closed:', err.message);
})
})
} else {
// display a message if browser is incompatible
console.error('EyeDropper API not supported in this browser.');
}
With the above code, you should see the color picker open when clicking the button!