Two new color notations are coming with the CSS Color Module Level 4 specification: lch()
and lab()
. They have a lot of advantages over the rgb or hsl colors we usually use, Lea Verou explains it very well. But, in order to be able to use them without breaking browser support, we need to be able to convert those notations to older notations, like rgb()
or color()
.
This repository is for the most part code written by Chris Lilley direclty in the CSS Color specification. It was then ported to typescript, and exposed as a package.
$ yarn add @color-spaces/convert
# or
$ npm i --save @color-spaces/convert
import { ColorSpace, convertCSSColor } from "@color-spaces/convert";
const myColorLCH = "lch(60% 67 266)";
// P3 colors are already supported by Safari
const myColorP3 = convertCSSColor(myColorLCH, ColorSpace.P3);
// RGB is supported everywhere
const myColorRGB = convertCSSColor(myColorLCH, ColorSpace.sRGB);
const CSS = `
:root {
--myColor: ${myColorRGB};
}
@supports (color: color(display-p3 1 1 1)) {
:root {
--myColor: ${myColorP3};
}
}
@supports (color: lch(0 0 0)) {
:root {
--myColor: ${myColorLCH};
}
}
`;
This enum contains all the supported color spaces:
- AdobeRGB
- HSL
- Lab
- LCH
- P3
- ProPhoto
- Rec2020
- sRGB
- XYZ
function convertCSSColor(CSSColor: string, to: CSSSpace): string;
- The
CSSColor
parameter is any CSS color, as a string. - The
to
parameter is any valid CSS color space – see theColorSpace
enum.
function convertColorToSpace(color: Color, to: ColorSpace): Color;
-
The
color
parameter is an object containing two keys:type
that represents itsColorSpace
.values
that is an array of numbers – i.e. [r,g,b] for the sRGB color space.
-
The
to
parameter is any color space fromColorSpace
.