Utility functions for parsing, converting and mixing colors in sRGB, CIE-XYZ, CIE-L*a*b*, and okLab color spaces
import { sRGB, XYZ, Lab, okLab, linearRGB } from '@4bitlabs/color-space';
const srgbColor = sRGB.create(255, 128, 0);
const xyzColor = XYZ.create(50.39, 57.009, 86.941);
const labColor = Lab.create(50.593, -49.586, 45.015);
const oklabColor = okLab.create(0.8, 0.144, 0.083);
const linearRGBColor = linearRGB.create(0.5, 0.5, 0.5);
The following package exports are available:
import * as sRGB from '@4bitlabs/color-space/srgb';
import * as XYZ from '@4bitlabs/color-space/xyz';
import * as CIELab from '@4bitlabs/color-space/lab';
import * as okLab from '@4bitlabs/color-space/oklab';
import * as linearRGB from '@4bitlabs/color-space/linear-rgb';
The color objects are backed by a simple-array that are easy and safe to serialize and deserialize, however you like. They also do not require any special parsing phase after deserialization, you can just use them like you normally would use them.
import { fromHex, toString } from '@4bitlabs/srgb';
const themeColor = fromHex('#ff6347');
const payload = { theme: { primaryColor: themeColor } };
const json = JSON.stringify(payload);
/* { "theme": { "primaryColor": ["sRGB", 255, 99, 71] } } */
const {
theme: { primaryColor },
} = JSON.parse(json);
console.log(toString(primaryColor)); // rgb(255 99 71);
If you are parsing from a untrusted or unverifed source, then you can use the included type-predicates to enforce proper structure:
import { toString, isSRGBTuple } from '@4bitlabs/srgb';
const {
theme: { primaryColor },
} = JSON.parse(json);
if (isSRGBTuple(primaryColor)) {
// primaryColor is definitely a sRGB color
console.log(toString(primaryColor)); // rgb(255 99 71);
}
sRGB
➡️ XYZ
import { sRGB } from '@4bitlabs/color-space';
const xyz = sRGB.toXYZ(color);
XYZ
➡️ Lab
:
import { XYZ } from '@4bitlabs/color-space';
const lab = XYZ.toLab(color);
XYZ
➡️ okLab
:
import { XYZ } from '@4bitlabs/color-space';
const oklab = XYZ.toOkLab(color);
okLab
➡️ XYZ
:
import { okLab } from '@4bitlabs/color-space';
const xyz = okLab.toXYZ(color);
Lab
➡️ XYZ
:
import { Lab } from '@4bitlabs/color-space';
const xyz = Lab.toXYZ(color);
XYZ
➡️ sRGB
:
import { XYZ } from '@4bitlabs/color-space';
const xyz = XYZ.toSRGB(color);
sRGB
➡️ linear-RGB
:
import { sRGB } from '@4bitlabs/color-space';
const linearRGB = sRGB.toLinearRGB(color);
linear-RGB
➡️ sRGB
:
import { linearRGB } from '@4bitlabs/color-space';
const sRBG = linearRGB.toSRGB(color);