petitecolor
v0.1.0
Published
Petite CSS Color Level 4 parser to sRGB / Display P3
Maintainers
Readme
petitecolor
A tiny CSS Color Level 4 parser. Parses any CSS color string and converts it to sRGB or Display P3 as a packed uint32 (0xRRGGBBAA). Under 4KB gzipped.
Install
npm install petitecolorUsage
import {toSRGB, toP3} from "petitecolor";
toSRGB("red"); // 0xff0000ff
toSRGB("#ff8800"); // 0xff8800ff
toSRGB("rgb(120, 30, 50)"); // 0x781e32ff
toSRGB("hsl(180, 50%, 50%)"); // 0x40bfbfff
toSRGB("oklch(0.6 0.2 30)"); // 0xde3e2dff
toSRGB("transparent"); // 0x00000000
toP3("red"); // 0xea3323ff (sRGB red in P3)
toP3("color(display-p3 1 0 0)"); // 0xff0000ffAPI
toSRGB(css: string): RGBA32
Parses a CSS color and returns a uint32 packed as 0xRRGGBBAA in the sRGB color space. Out-of-gamut values are clamped to [0, 255].
toP3(css: string): RGBA32
Same as toSRGB, but in the Display P3 color space.
Extracting channels
const c = toSRGB("coral");
const r = c >>> 24; // 255
const g = (c >> 16) & 0xff; // 127
const b = (c >> 8) & 0xff; // 80
const a = c & 0xff; // 255Writing to ImageData
const w = 360, h = 100;
const canvas = Object.assign(document.createElement("canvas"), {width: w, height: h});
const context = canvas.getContext("2d", {colorSpace: "display-p3"});
const imageData = context.getImageData(0, 0, w, h);
const view = new DataView(imageData.data.buffer);
for (let y = 0; y < h; ++y) {
const chroma = 0.3 * (1 - y / h);
for (let x = 0; x < w; ++x) {
view.setUint32((y * w + x) * 4, toP3(`oklch(0.7 ${chroma} ${x})`));
}
}
context.putImageData(imageData, 0, 0);Supported color syntaxes
- Named colors:
red,rebeccapurple,transparent - Hex:
#rgb,#rgba,#rrggbb,#rrggbbaa rgb()/rgba(): integers, percentages,nonehsl()/hsla(): degrees,grad,rad,turnhwb()lab()/lch()oklab()/oklch()color():srgb,srgb-linear,display-p3,a98-rgb,prophoto-rgb,rec2020,rec2100-pq,xyz-d65,xyz-d50
Both comma-separated (rgb(255, 0, 0)) and space-separated (rgb(255 0 0 / 0.5)) syntaxes are supported. Case-insensitive.
License
ISC
