parseToSpace
parseToSpace reads a CSS color into named numbers in the space it was written in. Read space first so TypeScript can tell you which channels are present.
Example
import { parseToSpace } from 'colore-js';
const value = parseToSpace('oklch(65% 0.18 280 / 80%)');
if (value.space === 'oklch') {
// The space tag lets TypeScript narrow the result.
[value.l, value.c, value.h, value.alpha].map((n) => Number(n.toFixed(2))); // [0.65, 0.18, 280, 0.8]
}
Syntax
parseToSpace(input: string): ParsedColorSpaceValue
Parameters
Returns
A frozen object with space, alpha and the named channels. Tiny differences can occur when coordinates are converted back to the source space.
Throws
A ColorError for an empty or invalid color, unsupported color() space, currentColor or color-mix(). Use parse to resolve supported mixes.
Read sRGB numbers on the CSS scale
Hex, named colors, rgb() and color(srgb …) all use space: 'srgb'. Extended channels in color(srgb …) can remain outside 0–1, while channels in rgb() are clamped.
import { parseToSpace } from 'colore-js';
parseToSpace('color(srgb 0.5 0 0.75)'); // {space: "srgb", r: 0.5, g: 0, b: 0.75, alpha: 1}
parseToSpace('color(srgb -0.2 0 1.1)'); // {space: "srgb", r: -0.2, g: 0, b: 1.1, alpha: 1}
Use colore(color).toObject(space) when you already know which space you want to convert into.
Related
- parse for a consistent linear shape
- Object output methods to convert into a space you choose
- Color spaces and ranges for channel units