Created
August 27, 2020 12:45
-
-
Save lucasconstantino/3b34f279b09585f50efae1a3fa3fff3f to your computer and use it in GitHub Desktop.
useImageColor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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