Mid-August the WICG published a (unofficial) specification for a Native Eye Dropper — a tool you can use to get the color from the pixel that’s underneath the cursor — on the web.
Let’s take a look …
~
Usage
The proposal is pretty straightforward:
This API enables authors to use a browser supplied eyedropper in the construction of custom color pickers.
It describes an EyeDropper
and a ColorSelectionResult
which you use as follows:
// Create an EyeDropper object
const eyeDropper = new EyeDropper();
document.getElementById("eyedropperButton").addEventListener('click', e => {
// Enter eyedropper mode
eyeDropper.open()
.then(colorSelectionResult => {
// returns hex color value (#RRGGBB) of the selected pixel
console.log(colorSelectionResult.sRGBHex);
})
.catch(error => {
// handle the user choosing to exit eyedropper mode without a selection
});
});
Upon clicking the button in the example above, an EyeDropper will open. After clicking, the color underneath will be captured and its outcome is a ColorSelectionResult
, of which you can current get the SRGB Hex Code via colorSelectionResult.sRGBHex
💡 As pointed out by reader Šime Vidas it’s worth nothing that you’re not limited to picking colors from the page itself, but from anywhere on your screen — even outside the browser window.
Live updating the color value as you move the cursor is currently not specced — it is, after all, a very young spec. This is considered a limitation and is being discussed in this GitHub Issue.
~
Demo
See the Pen
EyeDropper API Demo by Bramus (@bramus)
on CodePen.
Update 2021.09.01
Based on the contents of this post, Hakim El Hattab set out to integrate it into (the wonderful) Slides he’s been building:
Added an eye dropper to the @slides editor 🎨
Powered by Chrome's new EyeDropper API. Currently only available in Chrome 95 (Canary). pic.twitter.com/vDmMwMFS0E
— Hakim El Hattab (@hakimel) September 1, 2021
Very nice!
~
Browser Support
Whilst the API is still unofficial, it’s already supported in Chromium 95 (current Canary). Other Browsers (Firefox, Safari) have no support for it (yet). Relevant Issues to track:
- Chromium: Issue #897309
- Firefox: Issue #1728527
- Safari: Issue #229755
~
Extra: Quick one-liner
To open the EyeDropper with just one line of code you can use this snippet:
await new EyeDropper().open();
Handy for launching it from the Console, as demonstrated in the video below:
~
To help spread the contents of this post, feel free to retweet the announcement tweet:
Pick colors from websites with the EyeDropper API
🏷 #colors #javascript pic.twitter.com/coLaiymluu
— Bram.us (@bramusblog) September 1, 2021
~
🔥 Like what you see? Want to stay in the loop? Here's how:
🗣 This post originally was a set of tweets.