Colore JS

Search documentation

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

toHex

toHex turns a color into sRGB hex in JavaScript. Use it when an API, file or token needs a hex value. The conversion rounds channels to bytes and clips values outside sRGB.

Example

import { colore } from 'colore-js';
import { toHex } from 'colore-js/fn';

colore('rgb(37 99 235)').hex(); // '#2563eb'
toHex('rgb(37 99 235)'); // '#2563eb'

Convert OKLCH to hex

toHex reads oklch() the same way as any other CSS color. Alpha below 1 adds two more digits.

import { toHex } from 'colore-js/fn';

toHex('oklch(0.6 0.15 250)'); // '#2784d5'
toHex('hsl(221 83% 53%)'); // '#2463eb'
toHex('oklch(0.62 0.19 260 / 0.5)'); // '#3a81f680'

Some OKLCH colors, such as a high-chroma accent from a Tailwind CSS v4 theme, are outside sRGB, so hex can't hold them exactly. toHex clips each channel. Map the color into sRGB first to keep its lightness and hue closer to the original. It gives up some chroma instead.

import { colore } from 'colore-js';

const accent = colore('oklch(0.7 0.3 150)');
accent.hex(); // '#00cb00', clipped
accent.toGamut('srgb').hex(); // '#00c248', gamut-mapped

Syntax

colore(color).hex(): string
toHex(color: ColorInput): string

Parameters

NameTypeDescription
colorColorInputAny supported CSS color, tagged color object, Color instance or packed RGB number.

Returns

A lowercase #rrggbb string for an opaque color or #rrggbbaa when alpha is less than 1. Each output byte is rounded to an integer from 0 to 255.

Throws

A ColorError if the input is invalid.

Convert a Display P3 color to an sRGB token

If the input is outside sRGB, choose how you want to bring it into range. Direct conversion clips the channels. Gamut mapping can keep more of the color’s appearance before you round it to hex.

import { colore } from 'colore-js';

const green = colore('color(display-p3 0 1 0)');
green.hex(); // '#00ff00'
green.toGamut('srgb').hex(); // '#00fb29'

If your target accepts wide-gamut CSS, use toCss to keep the color in a suitable format.