Colore JS

Search documentation

Find a function or jump to a section.
v2.0.1

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

NameTypeDescription
inputstringA CSS color string in one of the spaces below.

Returns

A frozen object with space, alpha and the named channels. Tiny differences can occur when coordinates are converted back to the source space.

spaceChannels and units
srgb, p3r, g, b on a nominal gamma-encoded 0–1 scale.
hsl, hwbh in degrees, other channels in percent.
lab, lchl on 0–100, plus opponent channels or chroma and hue.
oklab, oklchl on 0–1, plus opponent channels or chroma and hue.

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.