It would be really great to have a colors category. A category responsible for colors method utilities like one that gets the best contrast of a color, returning either black or white hexadecimals. The method can be like:
function getBlackOrWhiteContrastColor(hex: string): string {
// Normalize the hex code to a 6-digit format if it's a 3-digit format
hex = hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, (_, r, g, b) => r + r + g + g + b + b);
// Convert hex to RGB
let [r, g, b] = hex.match(/\w\w/g)!.map(val => parseInt(val, 16));
// Calculate the relative luminance (perceived brightness) of the color
let luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
// Return black or white based on luminance
return luminance > 0.5 ? '#000' : '#fff';
}
Also, as an improvement, you can make the method more versatile. Accepting even RGB or RGBA colors 🙂
It would be really great to have a
colors
category. A category responsible for colors method utilities like one that gets the best contrast of a color, returning either black or white hexadecimals. The method can be like:Also, as an improvement, you can make the method more versatile. Accepting even RGB or RGBA colors 🙂