Chroma Panel

搜索文档

查找页面或章节

EN

选出易读的文字颜色,或按 WCAG 检测一组颜色。

对比度辅助函数可以为背景选出合适的文字颜色,或者按 WCAG 检测一组颜色。每个函数都接受 HSVA 值,或任何 parse 支持的字符串。这些函数在 React 和原生 JavaScript 中都能用。

不依赖 React 也能使用:

import { contrastReport, readableTextColor } from "chroma-panel/contrast";

选择文字颜色

readableTextColor("#001f3f"); // '#ffffff'

默认在黑色和白色之间选择。传入 darklight,就会改为在你自己的一对颜色之间选择。

function readableTextColor(background: string | Hsva, options?: { dark?: string; light?: string; }): string

Picks 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,并传入 levelsize

function contrastReport(a: string | Hsva, b: string | Hsva): ContrastReport

Everything 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): number

The WCAG 2.1 contrast ratio, from 1 to 21.

function meetsContrast(a: string | Hsva, b: string | Hsva, options: ContrastOptions): boolean

Whether 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): boolean

Whether 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): WcagLevel

The highest WCAG level a pair reaches, rather than a yes or no against one threshold.

底层的度量方法

function apcaContrast(text: string | Hsva, background: string | Hsva): number

The APCA lightness contrast, which models perceived contrast better than the WCAG ratio, particularly for light text on dark grounds.

function relativeLuminance(color: string | Hsva): number

The WCAG relative luminance of a color, the quantity the contrast ratio is built from.

为什么用 APCA 选文字颜色

readableTextColor 用的是 APCA,而不是单纯比较亮度。遇到中等明度的蓝色,它会选白色,而旧方法会错选黑色。