EyeDropper Web API
- Authors
- Name
- Austin Howard
- Published on
- Updated on
The EyeDropper API is a really cool feature, especially for any kind of creative applications. It allows you to select a color from the screen using a native eye dropper tool.
Example
Here's a simple example of how you can use the EyeDropper API in your web app:
At the time of writing this, the EyeDropper API is still experimental and supported in chromium based browsers. This also means there are no convenient Typescript lib definitions for it. So, we can bootstrap a simple .d.ts
file to get started:
// eye-dropper.d.ts
interface ColorSelectionOptions {
signal?: AbortSignal
}
interface ColorSelectionResult {
sRGBHex: string
}
interface EyeDropper {
open: (options?: ColorSelectionOptions) => Promise<ColorSelectionResult>
}
interface EyeDropperConstructor {
new (): EyeDropper
}
interface Window {
EyeDropper?: EyeDropperConstructor | undefined
}
Now, let's create a utility function to use the EyeDropper API:
// useEyeDropper.tsx
export const useEyeDropper = () => {
const isSupported = () => {
return 'EyeDropper' in window
}
return {
open: async () => {
if (isSupported()) {
// typescript is happy with window.EyeDropper
const eyeDropper = new window.EyeDropper()
return await eyeDropper.open()
}
},
}
}
Now that this is packaged up in a nice utility function, you can use it anywhere in your app. Here's an example of how you might use it in a React component:
// implementation
import { useEyeDropper } from '@/lib/colors/use-eyedropper'
export const EyeDropperCanvas = () => {
const { open } = useEyeDropper()
const handler = () => {
const canvas = document.getElementById('eyeDropperCanvas') as HTMLCanvasElement
const ctx = canvas.getContext('2d')
open().then((result) => {
if (ctx) {
ctx.fillStyle = result.sRGBHex
ctx.fillRect(0, 0, canvas.width, canvas.height)
}
})
}
return (
<div>
<legend>Click on the canvas to select a color</legend>
<canvas
id="eyeDropperCanvas"
style={{ border: '1px solid black', cursor: 'pointer', width: '100%', height: '300px' }}
onClick={handler}
></canvas>
</div>
)
}
Use Cases
Here are a few examples of things you might use the EyeDropper API in your web app:
- Color Picker: Allow users to select a color from the screen to use in your app.
- Color Contrast Checker: Check the contrast of a color against a background color.
- Color Palette Generator: Generate a color palette from an image.
- Color Theme Generator: Generate a color theme from an image.