# 序列化

> 把颜色转换为 hex、hexa、rgb、rgba、hsl 或 hsla 字符串。React 颜色选择器的 format prop 和表单值用的就是这些函数。

Source: https://chroma-panel.jscrate.dev/zh/react/utils/serializing
Last updated: 2026-09-21

序列化就是把 HSVA 值转换成 CSS 字符串。`toFormat` 通过参数指定格式。各个单独的辅助函数只返回一种格式，而 `toResult` 返回 `onChange` 使用的完整对象。

```ts
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` 字段，以及[表单提交的值](https://chroma-panel.jscrate.dev/zh/react/handbook/forms)。

## API 参考

```ts
function toFormat(hsva: Hsva, format: ColorFormat): string
```

Serializes 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.

### 单独输出一种格式

如果你清楚要哪种格式，每种格式都有对应的函数。

```ts
function toHex(hsva: Hsva): string
```

Six-digit hex, alpha discarded.

```ts
function toHexa(hsva: Hsva): string
```

Eight-digit hex, alpha included.

```ts
function toRgbString(hsva: Hsva): string
```

An `rgb()` string, alpha discarded.

```ts
function toRgbaString(hsva: Hsva): string
```

An `rgba()` string, alpha included.

```ts
function toHslString(hsva: Hsva): string
```

An `hsl()` string, alpha discarded.

```ts
function toHslaString(hsva: Hsva): string
```

An `hsla()` string, alpha included.

### 一次输出所有格式

```ts
function toResult(hsva: Hsva, format: ColorFormat): ColorChangeResult
```

Builds the full ColorChangeResult from an Hsva — every format at once. This is what change handlers receive.

> **精度**
>
> `hex` 会按每个通道 8 位取整。如果颜色需要在往返转换后保持不变，请保留 `hsva`。
