# 转换

> 在 HSVA、RGBA、HSLA 和 HWBA 之间转换颜色，极端值下也不丢失色相和饱和度。React 选择器内部用的就是这些函数。

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

这些函数用于在 HSVA、RGBA、HSLA 和 HWBA 对象之间转换。如果输入或输出是 CSS 字符串，请使用[解析](https://chroma-panel.jscrate.dev/zh/react/utils/parsing)和[序列化](https://chroma-panel.jscrate.dev/zh/react/utils/serializing)。结果不会取整，因此浮点数可能带有多余的小数位。

```ts
import { hsvaToRgba, hsvaToHsla, hslaToHsva } from "chroma-panel";
```

RGB 转 HSL 需要经过 HSVA：

```ts
import { rgbaToHsva, hsvaToHsla } from "chroma-panel";

hsvaToHsla(rgbaToHsva({ r: 51, g: 102, b: 204, a: 1 }));
// { h: 220, s: 60, l: 50, a: 1 }
```

## API 参考

```ts
function hsvaToRgba(hsva: Hsva): Rgba
```

HSVA to RGBA.

```ts
function rgbaToHsva(rgba: Rgba): Hsva
```

RGBA to HSVA. Hue is undefined at zero saturation, so this cannot round-trip a grayscale color on its own — see ingest.

```ts
function hsvaToHsla(hsva: Hsva): Hsla
```

HSVA to HSLA.

```ts
function hslaToHsva(hsla: Hsla & {
  a: number;
}): Hsva
```

HSLA to HSVA.

```ts
function hsvaToHwba(hsva: Hsva): Hwba
```

HSVA to HWBA.

```ts
function hwbaToHsva(hwba: Hwba): Hsva
```

HWBA to HSVA.

## 保留色相和饱和度

HSV 有两处会丢失信息。饱和度为零时，色相就无从谈起；亮度为零时，色相和饱和度都没有意义。从 HSVA 转成其他模型再转回来，这些信息就丢了。

如果颜色要经过另一种模型再转回来，请保留原始的 HSVA 值，把结果合并进去：

```ts
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.

## 比较与限制范围

```ts
function sameHsva(a: Hsva, b: Hsva): boolean
```

Whether two colors are equal channel for channel. Useful for skipping redundant work in a change handler.

```ts
function clamp(value: number, min: number, max: number): number
```

Constrains a number to a range.

```ts
function normalizeHue(h: number): number
```

Wraps a hue into 0-360, so 370 becomes 10.
