序列化就是把 HSVA 值转换成 CSS 字符串。toFormat 通过参数指定格式。各个单独的辅助函数只返回一种格式,而 toResult 返回 onChange 使用的完整对象。
import { toFormat } from "chroma-panel";
toFormat(hsva, "hex"); // '#3366cc'
toFormat(hsva, "rgba"); // 'rgba(51, 102, 204, 1)'
toFormat(hsva, "hsl"); // 'hsl(220, 60%, 50%)'可用的格式有 'hex'、'hexa'、'rgb'、'rgba'、'hsl' 和 'hsla'。format prop 背后用的也是这套转换,它决定了变更结果中的 css 字段,以及表单提交的值。
API 参考
function toFormat(hsva: Hsva, format: ColorFormat): stringSerializes a color in one of the six supported formats. This is what the format prop uses for the css field and the value a form submits.
单独输出一种格式
如果你清楚要哪种格式,每种格式都有对应的函数。
function toHex(hsva: Hsva): stringSix-digit hex, alpha discarded.
function toHexa(hsva: Hsva): stringEight-digit hex, alpha included.
function toRgbString(hsva: Hsva): stringAn rgb() string, alpha discarded.
function toRgbaString(hsva: Hsva): stringAn rgba() string, alpha included.
function toHslString(hsva: Hsva): stringAn hsl() string, alpha discarded.
function toHslaString(hsva: Hsva): stringAn hsla() string, alpha included.
一次输出所有格式
function toResult(hsva: Hsva, format: ColorFormat): ColorChangeResultBuilds the full ColorChangeResult from an Hsva — every format at once. This is what change handlers receive.
精度
hex 会按每个通道 8 位取整。如果颜色需要在往返转换后保持不变,请保留 hsva。