根据背景获取文字颜色
G18: Ensuring that a contrast ratio of at least 4.5:1 exists between text (and images of text) and background behind the text
G18: Ensuring that a contrast ratio of at least 4.5:1 exists between text (and images of text) and background behind the text
根据Web无障碍设计标准,文字颜色和背景需要满足一定的对比度:
WCAG G18: Ensuring that a contrast ratio of at least 4.5:1 exists between text (and images of text) and background behind the text
/**
* 获取文字对比色
* @param backgroundColor rgb(0,0,0)
* @returns rgb(255,255,255) | rgb(0,0,0)
*/
export function getContrastColor(backgroundColor: string) {
const rgb = backgroundColor.match(/\d+/g)!.map(Number)
const [r, g, b] = rgb.map((c) => {
const r = c / 255.0
if (r <= 0.03928) {
return r / 12.92
} else {
return Math.pow((r + 0.055) / 1.055, 2.4)
}
})
return 0.2126 * r + 0.7152 * g + 0.0722 * b > 0.179
? "rgb(0,0,0)"
: "rgb(255,255,255)"
}