### Start Documentation Server Source: https://github.com/evercoder/culori/blob/main/CONTRIBUTING.md Launch a local development server for the documentation website using the npm run docs:start script. ```bash npm run docs:start ``` -------------------------------- ### Install Culori using npm Source: https://github.com/evercoder/culori/blob/main/README.md Install the culori package using npm. This is the primary method for adding the library to your project. ```bash npm install culori ``` -------------------------------- ### Import Culori in Deno Source: https://github.com/evercoder/culori/blob/main/docs/getting-started.md Import Culori for use in Deno projects. This example shows how to import the library from deno.land/x. ```js import { rgb } from 'https://deno.land/x/culori@v{{pkg.version}}/index.js'; rgb('tomato'); ``` -------------------------------- ### Apply Easing Functions to Samples Source: https://github.com/evercoder/culori/blob/main/docs/api.md Shows how to map samples through easing functions to achieve different distributions. Includes examples for Bezier easing and easeInQuad. ```javascript import { samples } from 'culori'; import easing from 'bezier-easing'; // Bezier easing: let bezier = easing(0, 0, 1, 0.5); samples(10).map(bezier); // easeInQuad: samples(10).map(t => t * t); ``` -------------------------------- ### Color Difference Calculation Setup Source: https://github.com/evercoder/culori/blob/main/test/visual/gamut-mapping.html Sets up a JND (Just Noticeable Difference) scaling function and a function to widen color ranges. ```javascript const scaleJND = scalePow([0, 100], [0, 100], 4); const widen = (range, inc) => { return [range[0] * (1 + inc), range[1] * (1 + inc)]; }; ``` -------------------------------- ### Import and Use rgb Function Source: https://github.com/evercoder/culori/blob/main/docs/getting-started.md Import the rgb function from Culori and use it to convert color names to RGB objects. This example shows basic usage after installation. ```js import { rgb } from 'culori'; rgb('tomato'); // ⇒ Object { mode: "rgb", r: 1, g: 0.38823529411764707, b: 0.2784313725490196 } ``` -------------------------------- ### Custom Blend Function for Average Source: https://github.com/evercoder/culori/blob/main/docs/api.md Shows how to define a custom blending function for the 'blend' utility. This example creates an 'average' blend mode by averaging the backdrop and source color values. ```javascript import { blend } from 'culori'; blend(['red', 'green'], function average(b, s) { return (b + s) / 2; }); ``` -------------------------------- ### Minified esbuild output Source: https://github.com/evercoder/culori/blob/main/docs/guides/tree-shaking.md The minified JavaScript output generated by esbuild for the hex-to-hsl conversion example. ```javascript (function(){ var b=(e,o)=>{ if(typeof e=="number"){ if(o===3)return{mode:"rgb",r:(e>>8&15|e>>4&240)/255,g:(e>>4&15|e&240)/255,b:(e&15|e<<4&240)/255}; if(o===4)return{mode:"rgb",r:(e>>12&15|e>>8&240)/255,g:(e>>8&15|e>>4&240)/255,b:(e>>4&15|e&240)/255,alpha:(e&15|e<<4&240)/255}; if(o===6)return{mode:"rgb",r:(e>>16&255)/255,g:(e>>8&255)/255,b:(e&255)/255}; if(o===8)return{mode:"rgb",r:(e>>24&255)/255,g:(e>>16&255)/255,b:(e>>8&255)/255,alpha:(e&255)/255} } }, u=b; var c=/^#?([0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})$/i,x=e=>{ let o; return(o=e.match(c))?u(parseInt(o[1],16),o[1].length):void 0 }, l=x; function f({r:e,g:o,b:t,alpha:s}){ let r=Math.max(e,o,t), a=Math.min(e,o,t), i={mode:"hsl",s:r===a?0:(r-a)/(1-Math.abs(r+a-1)),l:.5*(r+a)} return r-a!=0&&(i.h=(r===e?(o-t)/(r-a)+(otypeof o=="number"?Math.round(o*(e=Math.pow(10,e)))/e:o } var n=p(2),d=e=>Math.max(0,Math.min(1,e)); var m=e=>{ if(e===void 0)return; let o=n(e.h||0), t=n(d(e.s)*100), s=n(d(e.l)*100) return e.alpha===void 0||e.alpha===1?`hsl(${o}, ${t}%, ${s}%)`:`hsla(${o}, ${t}%, ${s}%, ${n(d(e.alpha))}`) } console.log(m(f(l("#ffcc00")))); })() ``` -------------------------------- ### Use useMode to get color converter Source: https://github.com/evercoder/culori/blob/main/docs/guides/tree-shaking.md The `useMode()` function returns a converter for a specific color space. This is an alternative to the direct shortcuts like `culori.rgb`. ```javascript import { useMode, modeRgb } from 'culori/fn'; const rgb = useMode(modeRgb); console.log(rgb('tomato')); // ⇒ Object { mode: "rgb", r: 1, g: 0.38823529411764707, b: 0.2784313725490196 } ``` -------------------------------- ### HSL Color Space Definition Example Source: https://github.com/evercoder/culori/blob/main/docs/api.md This is a sample definition for the HSL color space, illustrating its mode, conversion functions, channels, ranges, parsing, serialization, interpolation, difference, and average functions. ```js { mode: 'hsl', fromMode: { rgb: convertRgbToHsl }, toMode: { rgb: convertHslToRgb }, channels: ['h', 's', 'l', 'alpha'], ranges: { h: [0, 360] }, parse: [parseHsl], serialize: serializeHsl, interpolate: { h: { use: interpolatorLinear, fixup: fixupHueShorter }, s: interpolatorLinear, l: interpolatorLinear, alpha: { use: interpolatorLinear, fixup: fixupAlpha } }, difference: { h: differenceHueSaturation }, average: { h: averageAngle } } ``` -------------------------------- ### Build Documentation Website Source: https://github.com/evercoder/culori/blob/main/CONTRIBUTING.md Generate a static build of the documentation website using the npm run docs:build script. ```bash npm run docs:build ``` -------------------------------- ### Deploy Documentation Source: https://github.com/evercoder/culori/blob/main/CONTRIBUTING.md Deploy the documentation website to GitHub Pages using the npm run docs:deploy script. ```bash npm run docs:deploy ``` -------------------------------- ### Import from culori/fn Source: https://github.com/evercoder/culori/blob/main/docs/guides/tree-shaking.md To optimize bundle size, import from `culori/fn` instead of `culori`. This requires manual registration of color spaces. ```javascript import { useMode, modeA98, modeHsl, modeHwb, modeLab, modeLch, modeOklab, modeOklch, modeP3, modeProphoto, modeRec2020, modeRgb, modeXyz50, modeXyz65 } from 'culori/fn'; const a98 = useMode(modeA98); const hsl = useMode(modeHsl); const hwb = useMode(modeHwb); const lab = useMode(modeLab); const lch = useMode(modeLch); const oklab = useMode(modeOklab); const oklch = useMode(modeOklch); const p3 = useMode(modeP3); const prophoto = useMode(modeProphoto); const rec2020 = useMode(modeRec2020); const rgb = useMode(modeRgb); const xyz50 = useMode(modeXyz50); const xyz65 = useMode(modeXyz65); ``` -------------------------------- ### HSL Interpolation Definition Source: https://github.com/evercoder/culori/blob/main/docs/api.md Example of how hue fixup is configured for HSL color space interpolation. This uses the default 'fixupHueShorter' method. ```javascript /* --- hsl/definition.js --- */ export default { // ... interpolate: { h: { use: interpolatorLinear, fixup: fixupHueShorter }, s: interpolatorLinear, l: interpolatorLinear, alpha: { use: interpolatorLinear, fixup: fixupAlpha } } // ... }; ``` -------------------------------- ### Import All Color Spaces and Interpolate Source: https://github.com/evercoder/culori/blob/main/docs/guides/tree-shaking.md Import all color spaces from 'culori/all' and use the interpolate function from 'culori/fn' to create a gradient between two colors in the 'xyb' color space. Ensure 'culori/all' is imported before using any color space functions. ```javascript import 'culori/all'; import { interpolate } from 'culori/fn'; interpolate(['red', 'green'], 'xyb'); ``` -------------------------------- ### Linear Interpolation Between Grays Source: https://github.com/evercoder/culori/blob/main/docs/api.md Creates an interpolator function for grayscale colors. Call the returned function with a value between 0 and 1 to get the interpolated color. ```javascript import { interpolate } from 'culori'; let grays = interpolate(['#fff', '#000']); grays(0.5); // ⇒ { mode: 'rgb', r: 0.5, g: 0.5, b: 0.5 } ``` -------------------------------- ### Import Culori in Observable Notebook Source: https://github.com/evercoder/culori/blob/main/docs/getting-started.md Import Culori into an Observable notebook. This allows for visual experimentation with the library. ```js culori = import('culori@{{pkg.version}}'); ``` -------------------------------- ### Calculate Euclidean distance between colors Source: https://github.com/evercoder/culori/blob/main/docs/api.md Use differenceEuclidean to get a function that calculates the Euclidean distance between two colors in a specified color space. Alpha channel is ignored by default. ```javascript import { differenceEuclidean } from 'culori'; // Default weights [1, 1, 1, 0] ignore alpha let euclideanDistance = differenceEuclidean('rgb'); // Include alpha in calculation let euclideanDistanceWithAlpha = differenceEuclidean('rgb', [1, 1, 1, 1]); console.log(euclideanDistance('red', 'blue')); console.log(euclideanDistanceWithAlpha('red', 'blue')); ``` -------------------------------- ### Importing color space converters Source: https://github.com/evercoder/culori/blob/main/docs/api.md Demonstrates the convenient way to import color space converters directly from the main `culori` package, such as `hsl`. ```javascript // Instead of this: import { converter } from 'culori'; const hsl = converter('hsl'); // You can do this: import { hsl } from 'culori'; ``` -------------------------------- ### Clamp Chroma in Different Color Spaces Source: https://github.com/evercoder/culori/blob/main/docs/api.md Demonstrates using `clampChroma` with different color spaces like 'oklch' and specifying the target RGB gamut. It also shows a strategy for using the color's own mode for clamping when possible. ```javascript import { clampChroma } from 'culori'; clampChroma({ mode: 'oklch', l: 0.5, c: 0.16, h: 180 }, 'oklch'); // ⇒ { mode: 'oklch', l: 0.5, c: 0.09, h: 180 } ``` ```javascript import { clampChroma } from 'culori'; clampChroma(color, color.c !== undefined ? color.mode : 'lch'); ``` -------------------------------- ### Check if Color is within RGB Gamut Source: https://github.com/evercoder/culori/blob/main/docs/api.md Use `inGamut` with 'rgb' to get a function that checks if a color is within the sRGB gamut. This is useful for identifying colors that cannot be accurately displayed on screen. ```javascript import { inGamut } from 'culori'; const inRgb = inGamut('rgb'); inRgb('red'); // ⇒ true inRgb('color(srgb 1.1 0 0)'); // ⇒ false ``` -------------------------------- ### Run Tests with Node.js Source: https://github.com/evercoder/culori/blob/main/CONTRIBUTING.md Execute project tests using the npm test script. Requires Node.js version 21 or newer. ```bash npm run test ``` -------------------------------- ### Clamp Color Chroma while Preserving Hue Source: https://github.com/evercoder/culori/blob/main/docs/api.md Use `clampChroma` to get a displayable color by adjusting its chroma. This method preserves the original hue and converts the result back to the original color space. It falls back to `clampRgb` if a displayable color cannot be found. ```javascript import { clampChroma } from 'culori'; clampChroma('lab(50% 100 100)'); // ⇒ { mode: 'lab', l:50.00…, a: 63.11…, b: 63.11… } ``` -------------------------------- ### Build Project Bundles Source: https://github.com/evercoder/culori/blob/main/CONTRIBUTING.md Generate project bundles in CommonJS, ESM, and UMD formats using esbuild via the npm run build script. ```bash npm run build ``` -------------------------------- ### Define a new color space with useMode Source: https://github.com/evercoder/culori/blob/main/docs/api.md Illustrates how to define a new color space using the `useMode` function, providing a definition object that includes the mode's properties and conversion functions. ```javascript import { useMode } from 'culori'; const hsl = useMode({ mode: 'hsl' // ... }); hsl('hsl(50 100% 100% / 100)'); ``` -------------------------------- ### Importing Gamut Mapping Functions Source: https://github.com/evercoder/culori/blob/main/test/visual/gamut-mapping.html Imports necessary functions for gamut mapping, color conversion, and utility functions from the culori library and local modules. ```javascript import { clampChroma, clampGamut, differenceEuclidean, dlch, getMode, inGamut, lch, lch65, oklch, rgb, toGamut } from '../../src/index.js'; import { toGamutCSSColor4, toGamutCSSColor4Smooth, toGamutFuzzy, toGamutCLReduce, toGamutNewton } from './gamut-mapping-algorithms.js'; import { formDataMap, draw, scaleLinear, scalePow } from './utils.js'; ``` -------------------------------- ### Apply Sepia Filter and Format Source: https://github.com/evercoder/culori/blob/main/docs/api.md Demonstrates applying a sepia filter to a gradient of colors and formatting the output as hex codes. This snippet uses `samples`, `interpolate`, `filterSepia`, and `formatHex`. ```javascript import { samples, interpolate, filterSepia, formatHex } from 'culori'; samples(5) .map(interpolate(['red', 'green', 'blue'])) .map(filterSepia(0.5)) .map(formatHex); // ⇒ ["#751800", "#664200", "#576c00", "#1a3e82", "#0010ff"]; ``` -------------------------------- ### Use Culori from CDN with Script Tag Source: https://github.com/evercoder/culori/blob/main/docs/getting-started.md Load Culori using a traditional script tag from a CDN. The library will be available under the global 'culori' variable. ```html ``` -------------------------------- ### parseOklab Source: https://github.com/evercoder/culori/blob/main/docs/api.md Parses `oklab(…)` strings and returns `oklab` color objects. ```APIDOC ## parseOklab ### Description Parses `oklab(…)` strings and returns `oklab` color objects. ### Method parseOklab(string) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```js import { parseOklab } from 'culori'; parseOklab('oklab(0.5, 0.2, 0.1)'); ``` ### Response #### Success Response (200) - **color** (object) - `oklab` color object #### Response Example None ``` -------------------------------- ### Convert Color to P3 Gamut Source: https://github.com/evercoder/culori/blob/main/docs/api.md Demonstrates converting a color string to the P3 color space using `toGamut`. The initial conversion shows the color outside the P3 gamut, while the second shows the gamut-mapped result. ```javascript import { p3, toGamut } from 'culori'; const color = 'lch(80% 150 60)'; p3(color); // ⇒ { mode: "p3", r: 1.229…, g: 0.547…, b: -0.073… } const toP3 = toGamut('p3'); toP3(color); // ⇒ { mode: "p3", r: 0.999…, g: 0.696…, b: 0.508… } ``` -------------------------------- ### Calculate hue contribution as shortest path around hue circle Source: https://github.com/evercoder/culori/blob/main/docs/api.md differenceHueNaive handles hue differences for color spaces like HWB by treating hues as numbers and applying the shortest path around the hue circle. This is a naive approach compared to other methods. ```javascript import { differenceHueNaive } from 'culori'; let colorA = { mode: 'hwb', h: 0.1, w: 0.5, b: 0.2 }; let colorB = { mode: 'hwb', h: 0.9, w: 0.5, b: 0.2 }; console.log(differenceHueNaive(colorA, colorB)); ``` -------------------------------- ### samples Source: https://github.com/evercoder/culori/blob/main/docs/api.md Generates an array of n equally-spaced samples in the [0, 1] range, useful for creating color scales with interpolate(). ```APIDOC ## samples ### Description Returns an array of _n_ equally-spaced samples in the `[0, 1]` range, with `0` and `1` at the ends. ### Method samples(n = 2) ### Parameters - **n** (number) - The number of samples to generate. Defaults to 2. ### Returns - Array - An array of n equally-spaced samples in the `[0, 1]` range. ### Example ```javascript import { samples } from 'culori'; samples(3); // ⇒ [0, 0.5, 1] samples(5); // ⇒ [0, 0.25, 0.5, 0.75, 1] ``` ``` -------------------------------- ### Use Culori from CDN as ES Module Source: https://github.com/evercoder/culori/blob/main/docs/getting-started.md Load Culori as an ES module from a CDN in an HTML script tag. This is useful for quick prototypes in the browser. ```html ``` -------------------------------- ### Interpolate with Easing Functions Source: https://github.com/evercoder/culori/blob/main/docs/api.md Demonstrates how to use easing functions to modify the interpolation between colors. Easing functions can be placed directly in the color array or applied globally. ```APIDOC ## Interpolate with Easing Functions ### Description Allows for custom easing functions to be applied between color stops in an interpolation. This provides fine-grained control over the transition speed and feel. ### Usage Easing functions can be inserted directly into the color array to affect the transition between the preceding and succeeding colors, or placed at the beginning of the array to apply to all transitions. ### Example 1: Individual Easing ```js import { interpolate } from 'culori'; const easeIn = t => t * t; interpolate(['red', easeIn, 'green']); ``` ### Example 2: Global Easing ```js import { interpolate } from 'culori'; const easeIn = t => t * t; // Applies easeIn between all color pairs interpolate([easeIn, 'red', 'green', 'blue']); ``` ### Example 3: Custom Interpolator with Easing ```js import { interpolate, interpolatorPiecewise, lerp } from 'culori'; const easeIn = t => t * t; interpolate( ['red', 'green', 'blue'], 'rgb', interpolatorPiecewise((a, b, t) => lerp(a, b, easeIn(t))) ); ``` ### Example 4: Per-Channel Easing ```js import { interpolate, interpolatorPiecewise, lerp } from 'culori'; function piecewiseEasing(easingFn) { return interpolatorPiecewise((a, b, t) => lerp(a, b, easingFn(t))); } interpolate(['red', 'green', 'blue'], 'rgb', { r: piecewiseEasing(easeIn), g: piecewiseEasing(easeOut), b: piecewiseEasing(easeInOut) }); ``` ``` -------------------------------- ### Convert hex to hsl string using low-level functions Source: https://github.com/evercoder/culori/blob/main/docs/guides/tree-shaking.md Demonstrates using low-level parsing and conversion functions from `culori/fn` to convert a hex color string to an HSL string without pre-registering color spaces. ```javascript import { parseHex, convertRgbToHsl, serializeHsl } from 'culori/fn'; console.log( serializeHsl( convertRgbToHsl( parseHex('#ffcc00') ) ) ); // ⇒ hsl(48, 100%, 50%) ``` -------------------------------- ### Generate Color Scales with Samples Source: https://github.com/evercoder/culori/blob/main/docs/api.md Uses the samples function to create a color scale by interpolating between two colors and formatting the output as hex codes. ```javascript import { samples, interpolate, formatHex } from 'culori'; let grays = interpolate(['#fff', '#000']); samples(5).map(grays).map(formatHex); // ⇒ ["#ffffff", "#bfbfbf", "#808080", "#404040", "#000000"] ``` -------------------------------- ### Registering custom color spaces in tree-shaken version Source: https://github.com/evercoder/culori/blob/main/docs/api.md When using the tree-shaken version of Culori (`culori/fn`), custom color spaces must be registered manually using `useMode` and their definition objects. ```javascript import { useMode, modeHsl } from 'culori/fn'; const hsl = useMode(modeHsl); ``` -------------------------------- ### Defining Gamut Mapping Methods Source: https://github.com/evercoder/culori/blob/main/test/visual/gamut-mapping.html Maps user-selectable method names to their corresponding gamut mapping functions, including built-in and custom implementations. ```javascript const METHODS = { clip: () => c => toRgb(c), css4: toGamutCSSColor4, 'css4-smooth': toGamutCSSColor4Smooth, fuzzy: toGamutFuzzy, 'chroma-reduce': function (gamut, space) { return c => clampChroma(c, space); }, 'cl-reduce': toGamutCLReduce, culori: toGamut, newton: toGamutNewton }; ``` -------------------------------- ### Interpolate with premultiplied alpha Source: https://github.com/evercoder/culori/blob/main/docs/api.md Use interpolateWithPremultipliedAlpha to interpolate colors with alpha premultiplied into the RGB channels. This differs from standard interpolation where alpha is separate. ```javascript import { interpolate, interpolateWithPremultipliedAlpha } from 'culori'; let colors = ['red', 'transparent', 'blue']; // alpha ignored for the R/G/B channels: interpolate(colors, 'rgb'); // alpha premultiplied into the R/G/B channels: interpolateWithPremultipliedAlpha(colors, 'rgb'); ``` -------------------------------- ### useParser Source: https://github.com/evercoder/culori/blob/main/docs/api.md Registers a new parser for the `color()` syntax. The parser can be a function or a string identifier for a mode. ```APIDOC ## useParser ### Description Register a new parser. The parser can be: * a function, in which case the _mode_ argument is not necessary. * a string representing the identifier to match in the `color()` syntax, in which case the _mode_ argument is required. ### Method useParser(parser, mode) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```js import { useParser } from 'culori'; // Register custom parser useParser(function(str) { let color = {}; // parse the string return color; }); // Register `color(--oklab)` syntax useParser('--oklab', 'oklab'); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Bootstrap CSS color spaces Source: https://github.com/evercoder/culori/blob/main/docs/guides/tree-shaking.md Importing `culori/css` bootstraps all CSS color spaces and related ones. This allows using functions like `interpolate` without manual registration. ```javascript import 'culori/css'; import { interpolate } from 'culori/fn'; interpolate(['red', 'green'], 'lch'); ``` -------------------------------- ### parseRgbLegacy Source: https://github.com/evercoder/culori/blob/main/docs/api.md Parses `rgb(…)` / `rgba(…)` strings in the legacy (comma-separated) syntax and returns `rgb` color objects. ```APIDOC ## parseRgbLegacy ### Description Parses `rgb(…)` / `rgba(…)` strings in the legacy (comma-separated) syntax and returns `rgb` color objects. ### Method parseRgbLegacy(string) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```js import { parseRgbLegacy } from 'culori'; parseRgbLegacy('rgb(255, 0, 0)'); ``` ### Response #### Success Response (200) - **color** (object) - `rgb` color object #### Response Example None ``` -------------------------------- ### Register Custom Parser by Mode String Source: https://github.com/evercoder/culori/blob/main/docs/api.md Use `useParser` with a string identifier to register a parser for a specific color syntax, like `color(--oklab)`. ```js import { useParser } from 'culori'; // Register `color(--oklab)` syntax useParser('--oklab', 'oklab'); ``` -------------------------------- ### useMode(definition) Source: https://github.com/evercoder/culori/blob/main/docs/api.md Defines a new color space and returns a converter function for it. ```APIDOC ## useMode(definition) ### Description Defines a new color space based on its _definition_. See [Color mode definition](#color-mode-def) for the expected object shape. Returns a converter function for the newly defined mode. ### Parameters #### Path Parameters - **definition** (object) - Required - The definition object for the new color space. ### Source [src/modes.js]({{codebase}}/src/modes.js) ### Example ```js import { useMode } from 'culori'; const hsl = useMode({ mode: 'hsl' // ... }); hsl('hsl(50 100% 100% / 100)'); ``` ``` -------------------------------- ### Custom Interpolation with Spline Basis Source: https://github.com/evercoder/culori/blob/main/docs/api.md Demonstrates how to use custom interpolation methods for specific channels, such as using 'interpolatorSplineBasis' for the hue channel in the LCH color space. ```javascript import { interpolate, interpolatorSplineBasis } from 'culori'; let my_interpolator = interpolate(['blue', 'red'], 'lch', { // spline instead of linear interpolation: h: interpolatorSplineBasis }); ``` -------------------------------- ### esbuild output for hex to hsl conversion Source: https://github.com/evercoder/culori/blob/main/docs/guides/tree-shaking.md The output of esbuild when bundling and minifying the hex-to-hsl conversion code. This showcases the resulting minified JavaScript. ```bash esbuild --bundle --minify hex-to-hsl-string.js ``` -------------------------------- ### Interpolate with Per-Channel Easing Source: https://github.com/evercoder/culori/blob/main/docs/api.md Apply different easing functions to individual color channels (r, g, b) for complex color transitions. This requires defining a helper function to wrap the easing logic for each channel. ```javascript import { interpolate, interpolatorPiecewise, lerp } from 'culori'; function piecewiseEasing(easingFn) { return interpolatorPiecewise((a, b, t) => lerp(a, b, easingFn(t))); } interpolate(['red', 'green', 'blue'], 'rgb', { r: piecewiseEasing(easeIn), g: piecewiseEasing(easeOut), b: piecewiseEasing(easeInOut) }); ``` -------------------------------- ### wcagContrast Source: https://github.com/evercoder/culori/blob/main/docs/api.md Computes the contrast ratio between two colors according to WCAG 2.0 specification. ```APIDOC ## wcagContrast ### Description Computes the contrast ratio between two colors. ### Method JavaScript Function ### Parameters - **colorA** (Color) - The first color. - **colorB** (Color) - The second color. ### Response - **contrastRatio** (number) - The contrast ratio between the two colors. ``` -------------------------------- ### interpolateWith Source: https://github.com/evercoder/culori/blob/main/docs/api.md Adds a pre-mapping and a post-mapping to an interpolation function. This is useful for advanced color interpolation scenarios like alpha premultiplication. ```APIDOC ## interpolateWith ### Description Adds a _pre-mapping_ and a _post-mapping_ to an interpolation, to enable things like alpha premultiplication. ### Method (Not specified, likely a function call) ### Parameters - **premap**: Function - The pre-mapping function to apply. - **postmap**: Function - The post-mapping function to apply. ### Request Example ```js import { interpolateWith, mapAlphaMultiply, mapAlphaDivide } from 'culori'; let interpolateWithAlphaPremult = interpolateWith( mapAlphaMultiply, mapAlphaDivide ); interpolateWithAlphaPremult(['red', 'transparent', 'blue'])(0.25); ``` ``` -------------------------------- ### parseRgb Source: https://github.com/evercoder/culori/blob/main/docs/api.md Parses `rgb(…)` strings in the modern syntax and returns `rgb` color objects. ```APIDOC ## parseRgb ### Description Parses `rgb(…)` strings in the modern syntax and returns `rgb` color objects. ### Method parseRgb(string) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```js import { parseRgb } from 'culori'; parseRgb('rgb(255, 0, 0)'); ``` ### Response #### Success Response (200) - **color** (object) - `rgb` color object #### Response Example None ``` -------------------------------- ### differenceHueNaive Source: https://github.com/evercoder/culori/blob/main/docs/api.md Computes the hue contribution to color difference for remaining color spaces like HWB, treating hues as numbers and applying the shortest path around the hue circle. ```APIDOC ## differenceHueNaive ### Description For remaining color spaces (HWB), we consider hues numbers, but apply a _shortest path around the hue circle_ (analogous to [`fixupHueShorter`](#fixupHueShorter)). If you insist on using Euclidean distances on these spaces, you can use the `weights` to control the contribution of the hue difference towards the total difference. ### Method (Not specified, likely a function call) ### Parameters - **colorA**: object | string - The first color. - **colorB**: object | string - The second color. ### Request Example ```js import { differenceHueNaive } from 'culori'; let hueNaiveDifference = differenceHueNaive('hwb(0, 0%, 100%)', 'hwb(120, 0%, 100%)'); ``` ``` -------------------------------- ### Calculate WCAG Contrast Ratio Source: https://github.com/evercoder/culori/blob/main/docs/api.md Computes the contrast ratio between two colors based on WCAG 2.0 guidelines. Import the `wcagContrast` function to use. ```javascript import { wcagContrast } from 'culori'; wcagContrast('red', 'black'); // ⇒ 5.252 ``` -------------------------------- ### Importing Culori with ES Modules (Node.js 12+) Source: https://github.com/evercoder/culori/blob/main/docs/guides/migration.md Use this import statement when using Node.js 12 or later with native ES modules. Ensure your package.json has 'type: module'. ```javascript import * as culori from 'culori'; ``` -------------------------------- ### Color Space Configuration Source: https://github.com/evercoder/culori/blob/main/docs/api.md Defines the structure for configuring custom color spaces, including parsing, serialization, interpolation, and difference methods. ```APIDOC ## Color Space Configuration Object ### Description This object allows for the definition and customization of color spaces within the Culori library. ### Properties #### `parse` (_array_, optional) Any parsers for the color space that can transform strings into colors. These can be either functions, or strings — the latter is used as the color space's identifier to parse the `color()` CSS syntax. #### `serialize` (_function_ or _string_, optional) Defines how to serialize the color space to a CSS string with [`formatCss()`](#formatCss). If you pass in a function, it receives a color object as its only argument, and should return a string that can be used in CSS. If you pass in a string, it's used as a color profile identifier, and the color is serialized using the `color()` CSS syntax. When omitted altogether, the default color profile identifier is `--${mode}`. #### `interpolate` The default interpolations for the color space, one for each channel. Each interpolation is defined by its interpolator (the `use` key) and its fixup function (the `fixup` key). When defined as a function, a channel interpolation is meant to define its interpolator, with the fixup being a no-op. #### `difference` The default Euclidean distance method for each channel in the color space; mostly used for the `h` channel in cylindrical color spaces. ``` -------------------------------- ### mapper Source: https://github.com/evercoder/culori/blob/main/docs/api.md Creates a mapping function that applies a given function `fn` to each channel of a color in a specified color space. ```APIDOC ## mapper ### Description Creates a mapping that applies _fn_ on each channel of the color in the _mode_ color space. The resulting function accepts a single argument (a color object or a string), which it converts to the _mode_ color space if necessary. The _mode_ parameter can be set to `null`, in which case the mapper will iterate through the channels in the color's original color space. ### Function Signature `mapper(fn, mode = "rgb")` ### Parameters - **fn**: A callback function with the signature `fn(value, channel, color, mode)` that processes each channel. - `value`: The current channel value. - `channel`: The name of the current channel. - `color`: A reference to the entire color object. - `mode`: The color space mode. - **mode**: The color space to map to (e.g., "rgb"). Defaults to "rgb". Can be `null` to use the color's original color space. ### Returns A function that takes a color and applies the mapping. ### Example ```js import { mapper } from 'culori'; const multiplyAlpha = mapper((val, ch, color) => { if (ch !== 'alpha') { return (val || 0) / (color.alpha !== undefined ? color.alpha : 1); } return val; }, 'rgb'); multiplyAlpha({ r: 1, g: 0.6, b: 0.4, a: 0.5 }); // ⇒ { mode: 'rgb', r: 0.5, g: 0.3, b: 0.2, a: 0.5 } ``` **Note**: Returning `undefined` or `NaN` from the callback function will omit that channel from the resulting color object. ``` -------------------------------- ### displayable Source: https://github.com/evercoder/culori/blob/main/docs/api.md Checks whether a particular color fits inside the sRGB gamut. This is equivalent to calling `inGamut('rgb')`. ```APIDOC ## displayable ### Description Checks whether a particular color fits inside the sRGB gamut. Equivalent to `inGamut('rgb')`. ### Method `displayable(color | string)` ### Parameters #### Path Parameters - **color** (color | string) - The color to check. ### Response Returns a boolean indicating whether the color is within the sRGB gamut. ### Request Example ```js import { displayable } from 'culori'; displayable('red'); // ⇒ true displayable('color(srgb 1.1 0 0)'); // ⇒ false ``` ``` -------------------------------- ### interpolateWithPremultipliedAlpha Source: https://github.com/evercoder/culori/blob/main/docs/api.md Creates an interpolation function that applies alpha premultiplication to the colors. It takes the same arguments as the standard interpolate function but ensures alpha is premultiplied into the RGB channels. ```APIDOC ## interpolateWithPremultipliedAlpha ### Description Takes the same arguments as [`interpolate()`](#interpolate), but applies [alpha premultiplication](https://drafts.csswg.org/css-images-4/#premultiplied). ### Method (Not specified, likely a function call) ### Parameters - **colors**: Array - An array of colors to interpolate between. - **mode**: string - The color space mode (default: 'rgb'). - **overrides**: object - Optional overrides for interpolation. ### Request Example ```js import { interpolate, interpolateWithPremultipliedAlpha } from 'culori'; let colors = ['red', 'transparent', 'blue']; // alpha ignored for the R/G/B channels: interpolate(colors, 'rgb'); // alpha premultiplied into the R/G/B channels: interpolateWithPremultipliedAlpha(colors, 'rgb'); ``` ``` -------------------------------- ### clampGamut Source: https://github.com/evercoder/culori/blob/main/docs/api.md Extends `clampRgb` functionality to other color spaces. Given a color space, it returns a function to obtain colors within that color space's gamut. Colors are returned in their original color space. ```APIDOC ## clampGamut ### Description This function extends the functionality of `clampRgb` to other color spaces. Given a color space, it returns a function with which to obtain colors within the gamut of that color space. If the color space has no gamut limits, colors are returned unchanged. The in-gamut color is always returned in the color space of the original color. ### Method `clampGamut(mode = 'rgb')` ### Parameters #### Path Parameters - **mode** (string) - Optional - The color space to clamp to. Defaults to 'rgb'. ### Response Returns a function that takes a color or string and returns a color within the specified gamut, in the original color space. ### Request Example ```js import { formatCss, clampGamut } from 'culori'; const crimson = 'color(display-p3 0.8 0.1 0.3)'; const toRgb = clampGamut('rgb'); formatCss(toRgb(crimson)); // ⇒ 'color(display-p3 0.801… 0.169… 0.302…)' ``` ``` -------------------------------- ### Creating Color Converters with converter() Source: https://github.com/evercoder/culori/blob/main/docs/api.md The `converter()` function returns a specialized function for converting colors to a specified mode. Converters can accept color strings or objects. ```javascript import { converter } from 'culori'; let rgb = converter('rgb'); let lab = converter('lab'); rgb('#f0f0f0'); // ⇒ { mode: "rgb", r: 0.49…, g: 0.49…, b: 0.49… } lab('#f0f0f0'); // ⇒ { mode: "lab", l: 94.79…, a: 0, b: 0 } ``` -------------------------------- ### Convert RGB to Oklab Source: https://github.com/evercoder/culori/blob/main/docs/api.md Converts a color from the RGB color space to the Oklab color space. ```APIDOC ## __convertRgbToOklab__ ### Description Converts a color from the RGB color space to the Oklab color space. ### Method __convertRgbToOklab__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **color** (color) - The color to convert. ### Request Example ```json { "example": "color" } ``` ### Response #### Success Response (color) - **color** (color) - The converted color in Oklab format. #### Response Example ```json { "example": "color" } ``` ``` -------------------------------- ### Importing Culori with CommonJS (Node.js 12+) Source: https://github.com/evercoder/culori/blob/main/docs/guides/migration.md Use this require statement when using Node.js 12 or later with CommonJS modules. This utilizes a separate export for compatibility. ```javascript const culori = require('culori/require'); ``` -------------------------------- ### Interpolate with Custom Interpolator and Easing Source: https://github.com/evercoder/culori/blob/main/docs/api.md Manually define the interpolation process using `interpolatorPiecewise` and `lerp` for advanced control, including custom easing functions. This method allows for fine-grained manipulation of the interpolation curve. ```javascript import { interpolate, interpolatorPiecewise, lerp } from 'culori'; const easeIn = t => t * t; interpolate( ['red', 'green', 'blue'], 'rgb', interpolatorPiecewise((a, b, t) => lerp(a, b, easeIn(t))) ); ``` -------------------------------- ### formatCss Source: https://github.com/evercoder/culori/blob/main/docs/api.md Returns a CSS string for the given color, based on the CSS Color Level 4 specification. Uses functional notation for supported color spaces like hsl or predefined spaces like display-p3. Other color spaces use the `color()` notation. ```APIDOC ## formatCss ### Description Returns a CSS string for the given color, based on the CSS Color Level 4 specification. A few color spaces, such as `hsl` or `lab`, have their own functional representation in CSS. We use that whenever possible; the `hsl` color space is represented as `hsl(h% s l / alpha)`. Predefined color spaces are represented using the `color()` notation with the appropriate identifier for the color space, e.g. `color(display-p3 r g b / alpha)`. All other colors spaces use the `color()` notation with a dashed identifier. For example, `jab` is represented as `color(--jzazbz j a b / alpha)`. Channel values are serialized as-is, with no change in the precision. To avoid compatibility issues, sRGB colors are represented as `color(srgb r g b / alpha)` rather than `rgb(r, g, b, alpha)`. For the latter, use the [`formatRgb()`](#formatRgb) method instead. An alpha of exactly `1` is omitted from the representation. **Note:** The strings returned by these methods are not widely supported in current browsers and should not be used in CSS as-is. ### Method N/A (Function Signature) ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { formatCss } from 'culori'; /* A mode with its own function notation. */ formatCss({ mode: 'hsl', h: 30, s: 1, l: 0.5, alpha: 0.5 }); // ⇒ 'hsl(30 100% 50% / 0.5)' /* A predefined color space. */ formatCss({ mode: 'p3', r: 0.5, s: 0.25, b: 1, alpha: 1 }); // ⇒ 'color(display-p3 0.5 0.25 1)' /* sRGB colors. */ formatCss({ mode: 'rgb', r: 0.5, g: 0.25, b: 1, alpha: 0.25 }); // ⇒ 'color(srgb 0.5 0.25 1 / 0.25)' /* A custom color space. */ formatCss({ mode: 'lrgb', r: 0.5, g: 0.25, b: 1, alpha: 0.25 }); // ⇒ 'color(--srgb-linear 0.5 0.25 1 / 0.25)' ``` ### Response #### Success Response - **string**: The CSS string representation of the color. #### Response Example ```json "hsl(30 100% 50% / 0.5)" ``` ``` -------------------------------- ### Custom Hue Interpolation with Identity Fixup Source: https://github.com/evercoder/culori/blob/main/docs/api.md Demonstrates how to disable hue fixup by providing an identity function, treating hues as normal numbers. This corresponds to the 'specified' fixup method. ```javascript import { interpolate } from 'culori'; let hsl_long = interpolate(['blue', 'red', 'green'], 'hsl', { h: { fixup: arr => arr } }); ``` -------------------------------- ### Convert Oklab to RGB Source: https://github.com/evercoder/culori/blob/main/docs/api.md Converts a color from the Oklab color space to the RGB color space. ```APIDOC ## __convertOklabToRgb__ ### Description Converts a color from the Oklab color space to the RGB color space. ### Method __convertOklabToRgb__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **color** (color) - The color to convert. ### Request Example ```json { "example": "color" } ``` ### Response #### Success Response (color) - **color** (color) - The converted color in RGB format. #### Response Example ```json { "example": "color" } ``` ``` -------------------------------- ### parseHwb Source: https://github.com/evercoder/culori/blob/main/docs/api.md Parses `hwb(…)` strings and returns `hwb` color objects. ```APIDOC ## parseHwb ### Description Parses `hwb(…)` strings and returns `hwb` color objects. ### Method parseHwb(string) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```js import { parseHwb } from 'culori'; parseHwb('hwb(120, 0%, 0%)'); ``` ### Response #### Success Response (200) - **color** (object) - `hwb` color object #### Response Example None ``` -------------------------------- ### Chain multiple mappings for interpolation Source: https://github.com/evercoder/culori/blob/main/docs/api.md Chain multiple mappings by composing them within the pre- and post-mapping arguments of interpolateWith. This allows for complex color transformations. ```javascript import { interpolateWith, mapAlphaMultiply, mapAlphaDivide } from 'culori'; const mapChromaMultiply = (v, ch, c, mode) => { // ... }; const mapChromaDivide = (v, ch, c, mode) => { // ... }; let interpolateWithAlphaChromaPremult = interpolateWith( (...args) => mapChromaMultiply(mapAlphaMultiply(...args)), (...args) => mapAlphaDivide(mapChromaDivide(...args)) ); interpolateWithAlphaChromaPremult(['red', 'transparent', 'blue'])(0.25); ``` -------------------------------- ### Interpolate with a Global Easing Function Source: https://github.com/evercoder/culori/blob/main/docs/api.md Apply the same easing function to all color transitions by placing it at the beginning of the color array. This simplifies interpolations with a consistent easing behavior. ```javascript import { interpolate } from 'culori'; const easeIn = t => t * t; // this form: interpolate([easeIn, 'red', 'green', 'blue']); // is equivalent to: interpolate(['red', easeIn, 'green', easeIn, 'blue']); ```