对比度辅助函数可以为背景选出合适的文字颜色,或者按 WCAG 检测一组颜色。每个函数都接受 HSVA 值,或任何 parse 支持的字符串。这些函数在 React 和原生 JavaScript 中都能用。
不依赖 React 也能使用:
import { contrastReport, readableTextColor } from "chroma-panel/contrast";选择文字颜色
readableTextColor("#001f3f"); // '#ffffff'默认在黑色和白色之间选择。传入 dark 和 light,就会改为在你自己的一对颜色之间选择。
function readableTextColor(background: string | Hsva, options?: {
dark?: string;
light?: string;
}): stringPicks black or white for text on the given background. Uses APCA rather than plain luminance, so it chooses white over mid-blues where the older method wrongly picks black.
检测一组颜色
WCAG 检查采用标准阈值:普通文字 AA 级为 4.5:1,AAA 级为 7:1;大号文字分别放宽到 3:1 和 4.5:1;UI 组件为 3:1。
wcagLevel 只根据对比度返回 'AAA'、'AA'、'AA Large' 或 'Fail',并会在开发环境中提示它已弃用。建议改用 meetsContrast,并传入 level 和 size。
function contrastReport(a: string | Hsva, b: string | Hsva): ContrastReportEverything WCAG says about a pair of colors at once: the contrast ratio, which text levels it passes at normal and large sizes, and whether it passes for non-text UI.
function contrastRatio(a: string | Hsva, b: string | Hsva): numberThe WCAG 2.1 contrast ratio, from 1 to 21.
function meetsContrast(a: string | Hsva, b: string | Hsva, options: ContrastOptions): booleanWhether a pair clears a WCAG level for text. The thresholds are 4.5:1 for AA and 7:1 for AAA, relaxed for large text.
function meetsNonTextContrast(a: string | Hsva, b: string | Hsva): booleanWhether a pair clears the 3:1 threshold WCAG applies to UI components and graphical objects rather than text.
function wcagLevel(a: string | Hsva, b: string | Hsva): WcagLevelThe highest WCAG level a pair reaches, rather than a yes or no against one threshold.
底层的度量方法
function apcaContrast(text: string | Hsva, background: string | Hsva): numberThe APCA lightness contrast, which models perceived contrast better than the WCAG ratio, particularly for light text on dark grounds.
function relativeLuminance(color: string | Hsva): numberThe WCAG relative luminance of a color, the quantity the contrast ratio is built from.
为什么用 APCA 选文字颜色
readableTextColor 用的是
APCA,而不是单纯比较亮度。遇到中等明度的蓝色,它会选白色,而旧方法会错选黑色。