Files
music-dl/web/src/getContrastYIQ.ts

26 lines
681 B
TypeScript

export function getContrastYIQ(hexcolor: string) {
// Remove leading # if present
if (hexcolor.startsWith("#")) {
hexcolor = hexcolor.slice(1);
}
// Handle 3-digit hex codes (e.g., #abc → #aabbcc)
if (hexcolor.length === 3) {
hexcolor = hexcolor
.split("")
.map((c) => c + c)
.join("");
}
// Parse RGB values
const r = parseInt(hexcolor.substring(0, 2), 16);
const g = parseInt(hexcolor.substring(2, 2), 16);
const b = parseInt(hexcolor.substring(4, 2), 16);
// Calculate YIQ brightness
const yiq = (r * 299 + g * 587 + b * 114) / 1000;
// Return black or white based on contrast
return yiq >= 128 ? "black" : "white";
}