Better contrast

This commit is contained in:
Koper
2023-11-30 21:29:08 +07:00
parent 2a4a636c27
commit 5dad782042

View File

@@ -98,26 +98,31 @@ export function murmurhash3_32_gc(key: string, seed: number = 0) {
export const generateHighContrastColor = ( export const generateHighContrastColor = (
name: string, name: string,
backgroundColor: [number, number, number] | null = null, backgroundColor: [number, number, number],
) => { ) => {
const hash = murmurhash3_32_gc(name); let loopNumber = 0;
let red = (hash & 0xff0000) >> 16; let minAcceptedContrast = 3.5;
let green = (hash & 0x00ff00) >> 8; while (true && /* Just as a safeguard */ loopNumber < 100) {
let blue = hash & 0x0000ff; ++loopNumber;
const getCssColor = (red: number, green: number, blue: number) => if (loopNumber > 5) minAcceptedContrast -= 0.5;
`rgb(${red}, ${green}, ${blue})`;
if (!backgroundColor) return getCssColor(red, green, blue); const hash = murmurhash3_32_gc(name + loopNumber);
let red = (hash & 0xff0000) >> 16;
let green = (hash & 0x00ff00) >> 8;
let blue = hash & 0x0000ff;
const contrast = getContrastRatio([red, green, blue], backgroundColor); let contrast = getContrastRatio([red, green, blue], backgroundColor);
// Adjust the color to achieve better contrast if necessary (WCAG recommends at least 4.5:1 for text) if (contrast > minAcceptedContrast) return `rgb(${red}, ${green}, ${blue})`;
if (contrast < 4.5) {
// Try to invert the color to increase contrat - this works best the more away the color is from gray
red = Math.abs(255 - red); red = Math.abs(255 - red);
green = Math.abs(255 - green); green = Math.abs(255 - green);
blue = Math.abs(255 - blue); blue = Math.abs(255 - blue);
}
return getCssColor(red, green, blue); contrast = getContrastRatio([red, green, blue], backgroundColor);
if (contrast > minAcceptedContrast) return `rgb(${red}, ${green}, ${blue})`;
}
}; };