Chroma Panel

搜索文档

查找页面或章节

EN

读取 CSS 颜色字符串,返回可直接使用的颜色值。

parse 读取 CSS 颜色字符串并返回 HSVA,输入无效时返回 null。如果校验时只要一个布尔值,就用 isValidColor。选择器的文本输入框用的也是这个解析器。

import { parse, isValidColor } from "chroma-panel";
 
parse("#3366cc");
parse("rgb(51 102 204)");
parse("hsl(220 60% 50%)");
parse("hwb(220 20% 20%)");
parse("oklch(72% 0.18 250)");
parse("color(display-p3 1 0.2 0.1)");
 
isValidColor("not a color"); // false

支持的格式包括 hex(3、4、6 和 8 位)、rgb()rgba()hsl()hsla()hwb()oklch()oklab()lab()lch()color(srgb …)color(display-p3 …)。hex 前面的 # 可以省略,色相可以使用 deggradradturn 单位,透明度可以是数字或百分比。transparent 关键字始终可用。

如果需要保留输入的色彩空间,而不是直接转成 HSVA,请使用 chroma-panel/color 中的 parseColor。详见 CSS Color 4

API 参考

function parse(input: string): Hsva | null

Turns any CSS color string into an Hsva, or null if it cannot be read. Hex, rgb(), hsl(), hwb() and the modern space-separated forms are all accepted; color names need registerNamedColors first.

function isValidColor(input: string): boolean

Whether parse would succeed, without building the result.

合并而不是替换

ingest 是面板内部使用的函数。它把修改合并进完整的 HSVA 值,而不是直接替换掉,色相和饱和度在极端值下能够保留,靠的就是这一点,详见在颜色模型之间转换

function ingest(next: Hsva, prev: Hsva): Hsva

Merges a change into an existing color rather than replacing it, keeping the hue and saturation that other models drop at the extremes. This is why dragging brightness to black and back returns the color you started with.

命名颜色

在你注册颜色名称之前,parse("rebeccapurple") 会返回 null。这些名称 gzip 后约 1.3 kB,所以需要手动启用,详见命名颜色

在 JavaScript 中解析 CSS 颜色字符串 | Chroma Panel