API
@pbroom/color-kit
The engine: OKLCH-canonical conversion, contrast, gamut mapping, harmony, manipulation and plane queries.
144 exports107 values37 types133 re-exportsalso @pbroom/color-kit/core
@pbroom/color-kit is the everyday import. Every function takes and returns the same
value, an OKLCH Color ({ l, c, h, alpha }), so results
compose without conversions in between. It runs in any JavaScript runtime and
has no React dependency. @pbroom/color-kit/core is an alias of this entry.
Domains
- Conversion.
parseandtryParseread any CSS Color 4 string;toCsswrites hex,rgb(),hsl(),oklch(),oklab()orcolor(display-p3 …).to*/from*pairs cover RGB, HSL, HSV, HCT, OKLab and Display P3, with allocation-free*Intovariants. - Gamut. Membership (
inSrgbGamut,inP3Gamut), mapping (toSrgbGamut,toP3Gamut) and geometry (maxChromaAt,gamutBoundaryPath). - Contrast. WCAG (
contrastRatio,meetsAA), APCA (contrastAPCA) and contrast regions (contrastRegionPaths). - Mixing and scales.
mix,interpolateandgenerateScaleuse OKLCH by default. Theirspaceoption accepts'oklch','oklab','srgb','linear-srgb','display-p3'and'linear-p3'.lightnessScalevaries OKLCH lightness while keeping chroma, hue and alpha fixed; it has no space option. - Manipulation and harmony.
lighten,adjustHue,complementaryand friends, all immutable.saturateanddesaturateclamp chroma only at 0, so wide-gamut colors keep chroma above0.4; map the result to a gamut when you need it on screen.
The root also re-exports the plane, interop and HCT helpers; their pages live under those entry points.
import {
contrastRatio,
inSrgbGamut,
parse,
toCss,
toSrgbGamut,
} from '@pbroom/color-kit';
const brand = parse('oklch(0.62 0.24 290)');
inSrgbGamut(brand); // → false
const shown = toSrgbGamut(brand); // chroma reduced, lightness and hue kept
toCss(shown, 'hex'); // → '#8a62ff'
// Measure the hex you ship: 8-bit channels, not the unrounded color.
const white = parse('#fff');
contrastRatio(shown, white, { precision: '8bit' }).toFixed(2); // → '3.98'Start with OKLCH-canonical colors and Requested vs displayed.
Types
- interface
ColorThe color value every color-kit API takes and returns: an OKLCH color. - interface
RgbGamma-encoded sRGB color with 0-255 channels. - interface
LinearRgbLinear-light sRGB color with nominal 0-1 channels. - interface
HslHSL color in the sRGB space. - interface
HsvHSV/HSB color in the sRGB space. - interface
HctMaterial Design HCT color (CAM16 hue and chroma, CIE L* tone). - interface
OklabOKLab color, the rectangular form of OKLCH (perceptually uniform). - interface
OklchOKLCH color, the cylindrical form of OKLab. - interface
P3Display P3 color (a wider gamut than sRGB) with 0-1 channels. - type
ColorSpaceSupported color space identifiers - interface
ParsedColorA parsed color with its original format preserved.
Conversion
- function
toRgbConvert a Color to 8-bit sRGB (0-255 per channel). - function
fromRgbConvert sRGB (0-255 per channel, fractional values allowed) to a Color. - function
toHexConvert a Color to a lowercase hex string: #rrggbb, or #rrggbbaa when alpha is below 1. - function
fromHexConvert a hex string (#rgb, #rgba, #rrggbb or #rrggbbaa; the # is optional) to a Color. - function
toHslConvert a Color to HSL (hue in degrees, saturation and lightness 0-100). - function
fromHslConvert HSL (hue in degrees, saturation and lightness 0-100) to a Color. - function
toHsvConvert a Color to HSV/HSB (hue in degrees, saturation and value 0-100). - function
fromHsvConvert HSV/HSB (hue in degrees, saturation and value 0-100) to a Color. - function
toHctConvert a Color to HCT (Material Design hue, chroma, tone). - function
fromHctConvert HCT (Material Design hue, chroma, tone) to a Color. - function
toOklabConvert a Color to OKLab (the rectangular form of OKLCH). - function
fromOklabConvert OKLab to a Color. - function
toOklchCopy a Color into a new Oklch object. - function
fromOklchCopy an Oklch value into a new Color. - function
toP3Convert a Color to gamma-encoded Display P3 (0-1 per channel). - function
fromP3Convert gamma-encoded Display P3 (0-1 per channel) to a Color. - function
toCssSerialize a Color as a CSS color string in the given format. - function
parseParse a CSS color string into a Color. - function
tryParseLike parse, but returns null instead of throwing when input is not a supported, well-formed CSS color (or not a string). - function
srgbToLinearConvert sRGB (0-255) to linear-light RGB (0-1) with the sRGB transfer function. - function
linearToSrgbConvert linear-light RGB (0-1) to 8-bit sRGB (0-255) with the sRGB transfer function. - function
rgbToHexConvert sRGB (0-255) to a lowercase hex string: #rrggbb, or #rrggbbaa when alpha is below 1. - function
hexToRgbParse a hex string (#rgb, #rgba, #rrggbb, #rrggbbaa; the leading # is optional) to 8-bit sRGB. - function
rgbToHslConvert sRGB (0-255, fractional values allowed) to HSL (hue in degrees [0, 360), saturation and lightness 0-100). - function
hslToRgbConvert HSL (hue in degrees, saturation and lightness 0-100) to 8-bit sRGB (0-255, each channel rounded to an integer). - function
rgbToHsvConvert sRGB (0-255, fractional values allowed) to HSV/HSB (hue in degrees [0, 360), saturation and value 0-100). - function
hsvToRgbConvert HSV/HSB (hue in degrees, saturation and value 0-100) to 8-bit sRGB (0-255, each channel rounded to an integer). - function
linearRgbToOklabConvert linear-light sRGB to OKLab. - function
oklabToLinearRgbConvert OKLab to linear-light sRGB. - function
oklabToOklchConvert OKLab to OKLCH. - function
oklchToOklabConvert OKLCH to OKLab (a = c·cos h, b = c·sin h). - function
oklchToColorConvert an Oklch value to a Color, normalizing the hue to [0, 360). - function
colorToOklchConvert a Color to an Oklch value, normalizing the hue to [0, 360). - function
linearSrgbToLinearP3Convert linear-light sRGB to linear-light Display P3 with the combined P3fromXYZ · sRGBtoXYZ matrix from CSS Color 4. - function
linearP3ToLinearSrgbConvert linear-light Display P3 to linear-light sRGB. - function
linearP3ToP3Gamma-encode linear-light Display P3 with the P3 transfer function (the same curve as sRGB). - function
p3ToLinearP3Linearize gamma-encoded Display P3 with the inverse P3 transfer function (the same curve as sRGB). - function
toOklabIntoConvert a Color to OKLab, writing into out (allocation-free). - function
fromOklabIntoConvert OKLab to a Color (OKLCH), writing into out (allocation-free). - function
toLinearSrgbIntoConvert a Color to unclamped linear-light sRGB (0-1, may fall outside that range for out-of-gamut colors), writing into out (allocation-free). - function
fromLinearSrgbIntoConvert linear-light sRGB to a Color, writing into out (allocation-free). - function
toRgbIntoConvert a Color to sRGB (0-255, rounded and clamped like toRgb), writing into out (allocation-free). - function
fromRgbIntoConvert sRGB (0-255) to a Color, writing into out (allocation-free). - function
toP3IntoConvert a Color to Display P3 (gamma-encoded, clamped to 0-1 like toP3), writing into out (allocation-free). - function
fromP3IntoConvert Display P3 (gamma-encoded, 0-1) to a Color, writing into out (allocation-free). - function
srgbToLinearIntoConvert sRGB (0-255) to linear RGB (0-1), writing into out (allocation-free). out may be the same object as rgb. - function
linearToSrgbIntoConvert linear RGB (0-1) to sRGB (0-255, rounded and clamped), writing into out (allocation-free). out may be the same object as linear. - function
linearRgbToOklabIntoConvert linear sRGB to OKLAB, writing into out (allocation-free). - function
oklabToLinearRgbIntoConvert OKLAB to linear sRGB, writing into out (allocation-free). - function
oklabToOklchIntoConvert OKLAB to OKLCH, writing into out (allocation-free). - function
oklchToOklabIntoConvert OKLCH to OKLAB, writing into out (allocation-free). - function
linearSrgbToLinearP3IntoConvert linear sRGB to linear Display P3, writing into out (allocation-free). - function
linearP3ToLinearSrgbIntoConvert linear Display P3 to linear sRGB, writing into out (allocation-free). out may be the same object as p3. - function
linearP3ToP3IntoApply Display P3 gamma encoding (same as sRGB transfer function), writing the clamped [0, 1] channels into out (allocation-free). out may be the same object as linear. - function
p3ToLinearP3IntoRemove Display P3 gamma encoding to get linear P3, writing into out (allocation-free). out may be the same object as p3. - const
LINEAR_SRGB_TO_LINEAR_P3Linear sRGB -> linear Display P3. - const
LMS_TO_LINEAR_SRGBLMS -> linear sRGB. - const
OKLAB_TO_LMSOKLab -> non-linear LMS'. - type
CssColorFormatOutput formats accepted by toCss. 'display-p3' serializes as color(display-p3 r g b). - type
Matrix3Full double-precision conversion matrices shared by the conversion and gamut modules.
Contrast
- function
relativeLuminanceReturns the WCAG 2.1 relative luminance of a color, from 0 (black) to 1 (white). - function
contrastRatioReturns the WCAG 2.1 contrast ratio between two colors, from 1 (identical luminance) to 21 (black on white). - function
contrastAPCAReturns the APCA (Advanced Perceptual Contrast Algorithm) lightness contrast of text on a background, as a normalized Lc value roughly between -1.08 and 1.06 (multiply by 100 for the conventional APCA Lc scale). - function
meetsAAReturns whether two colors meet WCAG 2.1 level AA: a contrast ratio of at least 4.5:1, or 3:1 when largeText is true. - function
meetsAAAReturns whether two colors meet WCAG 2.1 level AAA: a contrast ratio of at least 7:1, or 4.5:1 when largeText is true. - function
contrastRegionPathReturns the longest contour path (most points) of contrastRegionPaths, or [] when the region is empty. - function
contrastRegionPathsReturns the contour paths, in OKLCH lightness/chroma, that bound the region of colors at a fixed hue meeting the contrast criterion against reference. - function
clampContrastRegionSamplingReturns the sampling contrastRegionPaths actually runs with: defaults filled in (32, 0.0015, 6), initialSamples capped at 512, maxDepth at 12, and errorTolerance raised to at least 1e-6. - type
ContrastApcaPolarityWhich sign of APCA Lc passes a contrast region: - type
ContrastApcaPresetAPCA threshold preset, on the normalized scale contrastAPCA returns: 'body' is 0.6 (Lc 60), 'large-text' is 0.45 (Lc 45) and 'ui' is 0.3 (Lc 30). - type
ContrastApcaRoleWhich side of the APCA comparison the sampled color plays: 'sample-text' measures contrastAPCA(sample, reference), 'sample-background' measures contrastAPCA(reference, sample). - type
ContrastMetricContrast metric for contrast regions: 'wcag' uses contrastRatio, 'apca' uses contrastAPCA. - interface
ContrastOptionsOptions shared by relativeLuminance, contrastRatio, contrastAPCA, meetsAA and meetsAAA. - type
ContrastPrecisionChannel precision for contrast metrics. - type
ContrastRegionLevelWCAG contrast-ratio preset for contrast regions: 'AA' is 4.5:1, 'AAA' is 7:1 and 'AA-large' is 3:1. - interface
ContrastRegionPointA point on a contrast-region contour, in OKLCH lightness/chroma. - interface
ContrastRegionPathOptionsOptions for contrastRegionPaths, contrastRegionPath and the plane contrast queries. - interface
ContrastRegionSamplingSampling options as the contrast-region solver runs them, with defaults filled in and limits applied; returned by clampContrastRegionSampling.
Harmony
- function
complementaryReturn the complementary color: the OKLCH hue rotated 180°, with lightness, chroma and alpha unchanged. - function
analogousReturn analogous colors (neighbors on the OKLCH hue wheel): [hue - angle, color, hue + angle]. - function
triadicReturn triadic colors (three hues 120° apart on the OKLCH wheel): [color, hue + 120, hue + 240]. - function
tetradicReturn tetradic (square) colors: four hues 90° apart on the OKLCH wheel, [color, hue + 90, hue + 180, hue + 270]. - function
splitComplementaryReturn split-complementary colors: the base color plus the two hues angle degrees either side of its complement, [color, hue + 180 - angle, hue + 180 + angle].
Scale
- function
interpolateInterpolate between two Colors. t = 0 returns color1, t = 1 returns color2. - function
interpolateIntoAllocation-free interpolate(): writes the result into out and returns it. - function
generateScaleGenerate a color scale (array of colors) between two endpoints. - function
lightnessScaleGenerate a dark-to-light scale at the hue and chroma of color: steps colors with OKLCH lightness evenly spaced from range[0] to range[1] (both included).
Utilities
- const
ACHROMATIC_CHROMA_THRESHOLDOKLCH chroma at or below which a color is achromatic and its hue is powerless: the CSS Color 4 OKLCH epsilon (OKLab_to_OKLCH in the spec's sample code uses chroma <= 0.000004). - function
isAchromaticTrue when an OKLCH chroma is at or below ACHROMATIC_CHROMA_THRESHOLD (or is NaN), i.e. the hue is powerless. - function
clampClamp value to the inclusive range [min, max]. - function
roundRound value to decimals decimal places with Math.round (halves round up). - function
normalizeHueWrap a hue in degrees into [0, 360). - function
lerpLinearly interpolate from a to b. t = 0 gives a, t = 1 gives b; values outside [0, 1] extrapolate. - function
linearToSrgbChannelsRGB / Display P3 transfer function (gamma encoding): linear light to gamma-encoded, for one channel. - function
srgbToLinearChannelInverse sRGB / Display P3 transfer function (linearization): gamma-encoded to linear light, for one channel.
Interpolation
Manipulation
- function
lightenLighten a color by moving its OKLCH lightness toward white by a fraction of the remaining distance: l + amount * (1 - l), clamped to [0, 1]. - function
darkenDarken a color by scaling its OKLCH lightness toward black: l * (1 - amount), clamped to [0, 1]. - function
saturateIncrease chroma by an absolute fraction of the OKLCH chroma range: adds amount * 0.4, clamped below at 0. - function
desaturateDecrease chroma by a relative amount: c * (1 - amount), clamped below at 0. - function
adjustHueRotate the OKLCH hue by degrees (positive or negative), wrapping into [0, 360). - function
setAlphaReturn a copy of color with its alpha set to alpha, clamped to [0, 1]. - function
mixMix two colors together. t = 0 returns color1, t = 1 returns color2. - function
mixIntoAllocation-free mix(): writes the mix of color1 and color2 into out and returns it. - function
invertInvert a color in OKLCH: lightness becomes 1 - l and the hue rotates 180°, while chroma and alpha are kept. - function
grayscaleRemove all chroma (c = 0), keeping OKLCH lightness, hue and alpha, so the gray has the same perceived lightness as the input.
Gamut
- const
GAMUT_EPSILONShared floating-point margin for gamut boundary checks. - const
GAMUT_LINEAR_MAXUpper linear-light channel bound of the gamut membership test: linearize(1 + GAMUT_EPSILON) (≈ 1.0001706), the sRGB transfer function applied to an encoded channel of 1 + GAMUT_EPSILON. - const
GAMUT_LINEAR_MINLower linear-light channel bound of the gamut membership test: -GAMUT_EPSILON / 12.92 (≈ -5.805e-6), the linear value of an encoded channel at -GAMUT_EPSILON. - function
inSrgbGamutReturns whether an OKLCH color is inside the sRGB gamut. - function
isLinearRgbInGamutReturns whether unclamped linear-light RGB channels (linear sRGB or linear Display P3, which share the sRGB transfer function) lie inside the unit cube, allowing GAMUT_EPSILON of slack on the gamma-encoded channels: each channel must be within [GAMUT_LINEAR_MIN, GAMUT_LINEAR_MAX]. - function
inP3GamutReturns whether an OKLCH color is inside the Display P3 gamut. - function
toSrgbGamutMap a Color to the sRGB gamut. - function
toSrgbGamutIntoMap a Color to the sRGB gamut, writing the result into out (allocation-free). - function
toP3GamutMap a Color to the Display P3 gamut. - function
toP3GamutIntoMap a Color to the Display P3 gamut, writing the result into out (allocation-free). - function
maxChromaForHueReturns the hue cusp: the OKLCH lightness/chroma point with the maximum in-gamut chroma for a fixed hue. - function
maxChromaAtReturns the maximum in-gamut OKLCH chroma at a given lightness and hue. - function
gamutBoundaryPathSamples the OKLCH lightness/chroma gamut boundary at a fixed hue, from black (l: 0) to white (l: 1). - function
chromaBandReturns a tonal strip of OKLCH colors from black to white at a fixed hue, keeping each step inside the target gamut. - type
GamutTargetRGB gamut a query targets: 'srgb' or 'display-p3'. - type
GamutMapMethodGamut mapping algorithm for toSrgbGamut / toP3Gamut: - interface
GamutMapOptionsOptions for toSrgbGamut, toP3Gamut and their Into forms. - interface
GamutBoundaryPointA point on a gamut boundary path, in OKLCH lightness/chroma. - interface
HueCuspThe cusp of a hue slice: the OKLCH lightness/chroma point with the largest in-gamut chroma for that hue. - type
MaxChromaForHueMethodHow maxChromaForHue resolves the cusp: 'direct' solves it per call, 'lut' interpolates a cached hue lookup table. - interface
MaxChromaForHueOptionsOptions for maxChromaForHue. - interface
MaxChromaAtOptionsOptions for maxChromaAt; also accepted by gamutBoundaryPath and chromaBand. - interface
GamutBoundaryPathOptionsOptions for gamutBoundaryPath: the MaxChromaAtOptions search settings plus sampling controls. - type
ChromaBandModeHow chromaBand distributes chroma across lightness: 'clamped' keeps the requested chroma and clamps it to the boundary, 'proportional' scales the boundary chroma by a fixed ratio. - interface
ChromaBandOptionsOptions for chromaBand: the MaxChromaAtOptions search settings plus mode and sampling controls.
Re-exported here
@pbroom/color-kit also exports 133 symbols documented in a more specific entry point. Import them from either path; they are the same declarations.
@pbroom/color-kit/interop33- toLinearSrgbArray
- toLinearSrgbArray4
- toSrgbArray
- toSrgbArray4
- toLinearP3Array
- toLinearP3Array4
- toP3Array
- toP3Array4
- toOklabArray
- toOklabArray4
- toOklchArray
- toOklchArray4
- fromLinearSrgbArray
- fromLinearSrgbArray4
- fromSrgbArray
- fromSrgbArray4
- fromLinearP3Array
- fromLinearP3Array4
- fromP3Array
- fromP3Array4
- fromOklabArray
- fromOklabArray4
- fromOklchArray
- fromOklchArray4
- packColors
- unpackColors
- ArraySpace
- ArrayWriteOptions
- ColorTuple
- ColorTuple4
- PackColorsOptions
- UnpackColorsOptions
- WritableArrayLike
@pbroom/color-kit/plane94- assertGamutTarget
- Plane
- colorAtPlanePoint
- colorToPlane
- createPlaneQueryKey
- definePlane
- definePlaneFromColor
- getPlaneChromaBand
- getPlaneContrastBoundary
- getPlaneContrastRegion
- getPlaneFallbackPoint
- getPlaneGamutBoundary
- getPlaneGamutRegion
- inspectPlaneQueries
- inspectPlaneQuery
- PlaneQueryCache
- planeHue
- planeModelChannels
- planeModelDefaultRange
- planeToColor
- PLANE_MODEL_CHANNELS
- PLANE_MODEL_DEFAULT_AXES
- PLANE_MODEL_DEFAULT_RANGES
- resolvePlaneDefinition
- runCachedPlaneQuery
- runPlaneQueries
- runPlaneQuery
- samplePlaneGradient
- sense
- toSvgCompoundPath
- toSvgPath
- unionRegions
- intersectRegions
- differenceRegions
- nearestPointOnPath
- pointDistance
- containsPoint
- translateRegion
- scaleRegion
- rotateRegion
- projectRegionBetweenPlanes
- usesLightnessAndChroma
- PlaneAxis
- PlaneBooleanOptions
- PlaneBoundaryPoint
- PlaneChannelFor
- PlaneChromaBandQuery
- PlaneChromaBandResult
- PlaneColorPoint
- PlaneContrastBoundaryQuery
- PlaneContrastBoundaryResult
- PlaneContrastRegionQuery
- PlaneContrastRegionResult
- PlaneDefinition
- PlaneDefinitionFor
- PlaneFixedInput
- PlaneFallbackPointQuery
- PlaneFallbackPointResult
- PlaneGamutBoundaryQuery
- PlaneGamutBoundaryResult
- PlaneGamutRegionQuery
- PlaneGamutRegionResult
- PlaneGamutRegionScope
- PlaneContrastSolver
- PlaneGamutSolver
- PlaneGradientQuery
- PlaneGradientResult
- PlaneQueryInspection
- PlaneModelColor
- PlaneModel
- PlanePoint
- PlaneQuery
- PlaneQueryCacheOptions
- PlaneQueryResult
- PlaneQueryTrace
- PlaneQueryTraceCellEvent
- PlaneQueryTraceLevel
- PlaneQueryTraceMarchingSquaresStage
- PlaneQueryTraceMetricsStage
- PlaneQueryTraceOptions
- PlaneQueryTracePathStage
- PlaneQueryTraceScalarGridStage
- PlaneQueryTraceSolverStage
- PlaneQueryTraceStage
- PlaneQueryTraceSummary
- PlaneQueryTraceViewportStage
- PlaneSense
- PlaneRegion
- PlaneRegionPoint
- PlaneTraceBounds
- PlaneViewportRelation
- ResolvedPlaneAxis
- ResolvedPlaneDefinition
- SvgPathCompileOptions