Add hook for average color

This commit is contained in:
jeffvli 2022-12-29 16:50:05 -08:00
parent e50c59c903
commit 3ff46ce724
2 changed files with 38 additions and 0 deletions

View file

@ -2,3 +2,4 @@ export * from './use-theme';
export * from './use-is-mounted';
export * from './use-should-pad-titlebar';
export * from './use-container-query';
export * from './use-fast-average-color';

View file

@ -0,0 +1,37 @@
import { useEffect, useState } from 'react';
import { FastAverageColor } from 'fast-average-color';
export const useFastAverageColor = (
src?: string | null,
aglorithm?: 'dominant' | 'simple' | 'sqrt',
) => {
const [color, setColor] = useState('rgba(0, 0, 0, 0)');
useEffect(() => {
const fac = new FastAverageColor();
if (src) {
fac
.getColorAsync(src, {
algorithm: aglorithm || 'dominant',
ignoredColor: [
[255, 255, 255, 255], // White
[0, 0, 0, 255], // Black
],
mode: 'precision',
})
.then((color) => {
return setColor(color.rgb);
})
.catch((e) => {
console.log(e);
});
}
return () => {
fac.destroy();
};
}, [aglorithm, src]);
return color;
};