The EyeDropper API in Chromium-based browsers like Edge or Chrome can be a powerful tool for developers who want to sample colors from web pages and images. This API allows you to pick a color from a web page or image and get the color code for use in your own designs.
Feature Detection and Browser Support
Before you start using the EyeDropper API, make sure it's available in your browser.
The EyeDropper API is supported in Chromium-based browsers as of version 95.
Using the API
- To use the EyeDropper API, you first need to create an EyeDropper object and then call its open() method:
const eyeDropper = new EyeDropper();
- The
open()
method returns a promise that resolves after the user selects a pixel on the screen. The resolved value provides access to the pixel's color insRGBHex
format(#RRGGBB)
. If the user leaves the EyeDropper mode by pressing the esc key, the promise is rejected.
try {
const result = await eyeDropper.open();
// The user selected a pixel, here is its color:
const colorHexValue = result.sRGBHex;
} catch (err) {
// The user escaped the EyeDropper mode.
}
- If the app's state changes in a substantial way, the EyeDropper mode can be canceled. For example, if a popup dialog appears and requires the input of the user, the EyeDropper mode should be stopped. To cancel the EyeDropper mode, you can use an AbortController object's signal and pass it to the
open()
method.
const abortController = new AbortController();
try {
const result = await eyeDropper.open({signal: abortController.signal});
// ...
} catch (err) {
// ...
}
// And then later, when the EyeDropper mode needs to be stopped:
abortController.abort();
Here's a reusable async function that puts all the steps together:
async function sampleColorFromScreen(abortController) {
const eyeDropper = new EyeDropper();
try {
const result = await eyeDropper.open({signal: abortController.signal});
return result.sRGBHex;
} catch (e) {
return null;
}
}
References (Read More about the EyeDropper API here)
- https://developer.chrome.com/articles/eyedropper/
- https://developer.mozilla.org/en-US/docs/Web/API/EyeDropper
In conclusion, the EyeDropper API in Chromium-based browsers is a convenient tool for developers who want to sample colors from web pages and images. With its support for feature detection, promise-based functionality, and AbortController objects, it's an easy and effective way to get the color information you need.
Top comments (0)