Skip to content

Instantly share code, notes, and snippets.

@lucasconstantino
Created August 27, 2020 12:45
Show Gist options
  • Save lucasconstantino/3b34f279b09585f50efae1a3fa3fff3f to your computer and use it in GitHub Desktop.
Save lucasconstantino/3b34f279b09585f50efae1a3fa3fff3f to your computer and use it in GitHub Desktop.
useImageColor
const useImageColor = (throwOnError = false) => {
const [element, setElement] = useState<HTMLImageElement | null>(null)
const [color, setColor] = useState<string | null>(null)
const ref = useCallback(
(image: HTMLImageElement | null) => {
if (image) {
image.crossOrigin = 'Anonymous'
setElement(image)
}
},
[setElement]
)
useEffect(() => {
return element
? void new ImageColor()
.getColorAsync(element, {
ignoredColor: [0, 0, 0, 0],
// algorithm: 'dominant',
})
.then(({ hex }) => setColor(hex))
// die silently otherwise.
.catch((error) => {
if (throwOnError) {
throw error
}
})
: void 0
}, [element, throwOnError])
return [ref, color] as const
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment