Use The JavaScript EyeDropper API To Select Colors On The Web
The EyeDropper API just landed in Chrome Canary. In this is a mini tutorial we’ll quickly look at how to use it in our web apps to select colors.
Let’s get to it, the API is fairly straightforward.
We create a new EyeDropper
instance and can then ask it to open the eye dropper with the open
method.
The open
method returns a Promise that resolves when a color is selected, it rejects if the user cancels the color selection by pressing escape.
const eyeDropper = new EyeDropper();
try {
const selectedColor = await eyeDropper.open();
console.log(selectedColor);
// logs: { sRGBHex: '#ff0000' }
} catch (err) {
console.log('color selection cancelled');
}
You can test for support of EyeDropper
using the following snippet, if you’re browsing with a browser that supports the EyeDropper
API a button will be rendered below the code snippet.
if ('EyeDropper' in window) {
// supported
}
There we go! Fingers crossed we can start using this in the near future.