2023-09-27 16:00:26 +08:00

17 lines
564 B
TypeScript

/**
* Choose fg color by bg color
* @see https://www.npmjs.com/package/colord
* @see https://www.w3.org/TR/AERT/#color-contrast
*/
export function pickTextColor(
bgColor: string,
lightColor: string,
darkColor: string
) {
const color = bgColor.charAt(0) === "#" ? bgColor.substring(1, 7) : bgColor;
const r = parseInt(color.substring(0, 2), 16); // hexToR
const g = parseInt(color.substring(2, 4), 16); // hexToG
const b = parseInt(color.substring(4, 6), 16); // hexToB
return r * 0.299 + g * 0.587 + b * 0.114 > 186 ? darkColor : lightColor;
}