### Install Project Dependencies
Source: https://github.com/color-js/color.js/blob/main/CONTRIBUTING.md
Run this command in the project directory after cloning to install all necessary local modules.
```bash
npm install
```
--------------------------------
### Watch and Build HTML with Development Server
Source: https://github.com/color-js/color.js/blob/main/CONTRIBUTING.md
Builds HTML files and starts a development server, automatically rebuilding as files are edited.
```bash
npm run watch:html
```
--------------------------------
### Install Color.js via npm
Source: https://github.com/color-js/color.js/blob/main/README.md
Install Color.js using npm for project integration. This is the standard method for managing dependencies in modern JavaScript projects.
```bash
npm install colorjs.io
```
--------------------------------
### Matrix Multiplication Test Setup
Source: https://github.com/color-js/color.js/blob/main/tests/multiply-matrices.html
Sets up helper functions for matrix string conversion, HTML rendering, and reference multiplication using math.js. It also assigns these functions and predefined matrices to the global scope for testing.
```javascript
import multiplyMatrices from "../src/multiply-matrices.js";
function matrixToString(M) {
if (Array.isArray(M)) {
if (Array.isArray(M[0])) {
return M.map(x => x.join("\t")).join("\n");
} else {
return M.join("\t");
}
}
return M;
}
function matrixHTML(M) {
return `
${matrixToString(M)}
`;
}
function refMultiply(A, B) {
return matrixHTML(math.multiply(math.matrix(A), math.matrix(B)).valueOf())
}
function testMultiply(A, B) {
return matrixHTML(multiplyMatrices(A, B));
}
Object.assign(globalThis, {
refMultiply,
testMultiply,
M_lin_sRGB_to_XYZ: [
[0.4124564, 0.3575761, 0.1804375],
[0.2126729, 0.7151522, 0.0721750],
[0.0193339, 0.1191920, 0.9503041]
],
M_XYZ_to_lin_sRGB: [
[3.2404542, -1.5371385, -0.4985314],
[-0.9692660, 1.8760108, 0.0415560],
[0.0556434, -0.2040259, 1.0572252]
],
});
async function reftest(A, B) {
let script = document.currentScript;
$.ready().then(() => {
let ref, test;
try {
ref = matrixHTML(refMultiply(A, B))
} catch (e) {
ref = e
}
try {
test = matrixHTML(multiplyMatrices(A, B))
} catch (e) {
test = e
}
script.after(
$.create("td", { innerHTML: ref }),
$.create("td", { innerHTML: test})
);
});
}
```
--------------------------------
### Get Color Coordinates
Source: https://github.com/color-js/color.js/blob/main/tests/conversions.html
Examples of retrieving specific color coordinates (like 'c' or 'lch') from a Color object. Ensure the Color object is initialized correctly.
```javascript
$out(() => { var color = new Color("slategray"); return color.c });
```
```javascript
$out(() => { var color = new Color("slategray"); return color.lch[1]; });
```
```javascript
$out(() => { var color = new Color("slategray"); return color.lch.c; });
```
```javascript
$out(() => { var color = new Color("slategray"); return color.oklch.c; });
```
```javascript
$out(() => { var color = new Color("color(jzazbz 0.54 0 0)"); return color.jzazbz.jz });
```
--------------------------------
### Get Displayable CSS Color with `display()` Method
Source: https://github.com/color-js/color.js/blob/main/docs/output.md
Utilize the `color.display()` method for a simplified way to get a CSS-compatible color string. This method automatically handles fallbacks to supported color spaces, preserving gamut as much as possible.
```js
let green = new Color("lch", [80, 80, 120]);
let cssColor = green.display();
let cssColor2 = green.display({space: "hsl"});
```
--------------------------------
### Jzazbz to JzCzHz conversion
Source: https://github.com/color-js/color.js/blob/main/tests/conversions.html
Converts colors from Jzazbz to JzCzHz. Includes examples with near-zero values and specific coordinate combinations.
```javascript
convertToJzCzHz();
```
--------------------------------
### Gamut Mapping and Checking
Source: https://github.com/color-js/color.js/blob/main/docs/the-color-object.md
Check if a color is within the gamut of a target color space using `inGamut()` and get gamut-mapped coordinates using `toGamut()`. `toString()` defaults to gamut mapping.
```javascript
let funkyLime = new Color("p3", [0, 1, 0]);
let boringLime = funkyLime.to("srgb");
boringLime.coords;
boringLime.inGamut();
boringLime.toGamut();
```
--------------------------------
### Build Project
Source: https://github.com/color-js/color.js/blob/main/CONTRIBUTING.md
Executes a one-time build of the entire project, including CSS, HTML, and JavaScript bundling.
```bash
npm run build
```
--------------------------------
### Get Gamut Mapped Coordinates
Source: https://github.com/color-js/color.js/blob/main/docs/gamut-mapping.md
Use `toGamut()` to get the gamut-mapped coordinates of a color. This method mutates the color object. To avoid mutation, clone the color first. You can specify the target gamut space and the mapping method.
```javascript
let lime = new Color("p3", [0, 1, 0]);
let sRGB_lime = lime.to("srgb");
lime.toGamut({space: "srgb"});
sRGB_lime.clone().toGamut();
sRGB_lime; // still out of gamut
```
--------------------------------
### Create Color Objects Manually
Source: https://github.com/color-js/color.js/blob/main/README.md
Shows how to instantiate Color objects by providing the color space and coordinates, or a configuration object.
```javascript
let color2 = new Color("hwb", [60, 30, 40], .5);
let color3 = new Color({space: "p3", coords: [0, 1, 0], alpha: .9});
```
--------------------------------
### Watch and Bundle JavaScript Files
Source: https://github.com/color-js/color.js/blob/main/CONTRIBUTING.md
Bundles Color.js into the dist/ directory and watches for changes, automatically rebuilding upon modification.
```bash
npm run watch:js
```
--------------------------------
### Import and Initialize Adaptation Functions
Source: https://github.com/color-js/color.js/blob/main/tests/adapt.html
Imports necessary constants and functions for chromatic adaptation and makes them globally available.
```javascript
import {WHITES} from "../src/adapt.js"; import {adapt} from "../src/CATs.js"; window.WHITES = WHITES; window.color_adapt = adapt;
```
--------------------------------
### Get Coordinates in Different Color Spaces
Source: https://github.com/color-js/color.js/blob/main/docs/the-color-object.md
Access the color's coordinates in any other supported color space by using the color space ID as a property of the Color object.
```javascript
let color = new Color("deeppink");
color.srgb;
color.p3;
color.lch;
color.lab;
color.prophoto;
```
--------------------------------
### Lint and Format Project Code
Source: https://github.com/color-js/color.js/blob/main/CONTRIBUTING.md
Runs ESLint to check code style and format the project according to the defined rules in .eslintrc.json.
```bash
npm run lint
```
--------------------------------
### Import Color.js from CDN
Source: https://github.com/color-js/color.js/blob/main/README.md
Use this snippet to quickly import Color.js from a CDN for experiments. Ensure you are using a module-compatible script tag in your HTML.
```js
import Color from "https://esm.sh/colorjs.io";
```
--------------------------------
### Control Gamut Mapping String Representation
Source: https://github.com/color-js/color.js/blob/main/docs/gamut-mapping.md
By default, the string representation of a Color object is gamut-mapped. Use the `inGamut: false` option in `toString()` to disable this behavior and get the raw coordinates.
```javascript
let lime = new Color("p3", [0, 1, 0]).to("srgb");
lime.coords;
lime.toString();
lime.toString({inGamut: false});
```
--------------------------------
### One-Time JavaScript Build
Source: https://github.com/color-js/color.js/blob/main/CONTRIBUTING.md
Performs a single build of the Color.js JavaScript bundles without continuous watching.
```bash
npm run build:js
```
--------------------------------
### XYZ Scaling Chromatic Adaptation (Not Recommended)
Source: https://github.com/color-js/color.js/blob/main/docs/adaptation.md
Demonstrates the concept of XYZ scaling for chromatic adaptation. This method is simple but does not accurately predict corresponding colors and is not recommended for practical use.
```javascript
let W1 = Color.WHITES.D65;
let W2 = Color.WHITES.D50;
let Xscale = W1[0]/W2[0];
let Zscale = W1[2]/W2[2];
let color = new Color("rebeccapurple");
let color2 = color.xyz /// aah nevermind this isn't going to work
```
--------------------------------
### Mixing Colors
Source: https://github.com/color-js/color.js/blob/main/docs/interpolation.md
Create color mixtures in specific proportions using `color.mix()` and `Color.mix()`. This is a shortcut for specific points in a color range.
```APIDOC
## color.mix()
### Description
Mixes the current color with another color at a specified proportion.
### Method
Instance method of a Color object.
### Parameters
- **otherColor** (Color | string) - The color to mix with.
- **proportion** (number) - The proportion of the `otherColor` to use (0 to 1). 0 means only the current color, 1 means only `otherColor`.
- **options** (object, optional) - Configuration options for mixing.
- **space** (string, optional) - The color space in which to perform mixing. Defaults to 'lab'.
- **outputSpace** (string, optional) - The color space for the output color. Defaults to the input color's space.
### Request Example
```js
let color = new Color("p3", [0, 1, 0]);
let redgreen = color.mix("red", .5, {space: "lch", outputSpace: "srgb"});
let reddishGreen = color.mix("red", .25, {space: "lch", outputSpace: "srgb"});
```
## Color.mix()
### Description
Static method to mix two colors at a specified proportion.
### Method
Static method of the Color class.
### Parameters
- **color1** (Color | string) - The first color.
- **color2** (Color | string) - The second color.
- **proportion** (number) - The proportion of the `color2` to use (0 to 1).
- **options** (object, optional) - Configuration options for mixing. Same as `color.mix()`.
### Request Example
```js
Color.mix("color(display-p3 0 1 0)", "red", .5);
```
```
--------------------------------
### Importing and Using Procedural Functions
Source: https://github.com/color-js/color.js/blob/main/docs/procedural.md
Import multiple functions at once or individually from 'colorjs.io/fn'. Register color spaces like sRGB, P3, and LCH for parsing and conversion. Use functions like parse, convert (aliased as 'to'), toGamut, and serialize to manipulate colors represented as plain objects.
```javascript
// Import multiple functions at once
import {
to as convert,
toGamut,
serialize,
ColorSpace,
sRGB,
P3,
LCH
} from "colorjs.io/fn";
// You can also import functions directly:
import parse from "./node_modules/colorjs.io/src/parse.js";
// Register color spaces for parsing and converting
ColorSpace.register(sRGB); // Can parse keywords and hex colors
ColorSpace.register(P3);
ColorSpace.register(LCH); // Used in toGamut and serialize
// Parsing color
const red = parse("red");
// Directly creating object literal
const p3_lime = {space: "p3", coords: [0, 1, 0]};
const p3_lime_srgb = convert(p3_lime, "srgb");
const lime_in_gamut = toGamut(p3_lime_srgb);
const lime_str = serialize(p3_lime_srgb);
```
--------------------------------
### Dynamic Test Runner Logic
Source: https://github.com/color-js/color.js/blob/main/test/index.html
Handles loading test files specified in the URL. It appends '.js' if no extension is found and formats the path for local imports. It then dynamically imports the test module and a renderer, executing the test.
```javascript
let params = new URLSearchParams(location.search);
let test_url = params.get('test');
if (test_url) {
let test_url_ext = test_url.match(/\.w+$/)?.["1"];
if (!test_url_ext) {
test_url += '.js';
}
if (/^\w+\.\w+$/.test(test_url)) {
test_url = `./${test_url}`;
}
Promise.all([
import("../node_modules/htest.dev/src/render.js").then(m => m.default),
import(test_url).then(m => m.default),
]).then(([render, test]) => render(test));
}
```
--------------------------------
### Specify Output Format
Source: https://github.com/color-js/color.js/blob/main/docs/output.md
Use the `format` option in `toString()` to select specific output formats like 'rgb', 'rgba', 'hex', or 'color'.
```javascript
let lv_magenta = new Color("#ff0066");
lv_magenta.toString({format: "rgb"});
lv_magenta.toString({format: "rgba"});
lv_magenta.toString({format: "hex"});
lv_magenta.toString({format: "color"});
```
--------------------------------
### Create Color Objects from CSS Color Strings
Source: https://github.com/color-js/color.js/blob/main/README.md
Demonstrates creating Color objects from various CSS Color Level 4 string formats. Ensure the Color class is imported.
```javascript
let color = new Color("slategray");
let color2 = new Color("hwb(60 30% 40% / .5)");
let color3 = new Color("color(display-p3 0 1 0 / .9)");
let color4 = new Color("lch(50% 80 30)");
```
--------------------------------
### Generate Discrete Color Steps
Source: https://github.com/color-js/color.js/blob/main/docs/interpolation.md
Use `color.steps()` to obtain an array of discrete color steps between two colors. Options include specifying the interpolation space, output space, maximum delta E between steps, and minimum number of steps.
```javascript
let color = new Color("p3", [0, 1, 0]);
color.steps("red", {
space: "lch",
outputSpace: "srgb",
maxDeltaE: 3, // max deltaE between consecutive steps (optional)
steps: 10 // min number of steps
});
```
--------------------------------
### Calculate Contrast using WCAG 2.1
Source: https://github.com/color-js/color.js/blob/main/docs/contrast.md
Calculate the contrast between two colors using the WCAG 2.1 algorithm. The general `contrast()` function can also be used by specifying the algorithm name.
```javascript
let color1 = new Color("p3", [0.9, 0.8, 0.1]);
let color2 = new Color("slategrey");
let contrast = color1.contrastWCAG21(color2);
let sameContrast = color1.contrast(color2, "WCAG21");
// Case insensitive:
let sameContrast2 = color1.contrast(color2, "wcag21");
```
--------------------------------
### Out of Gamut Conversions
Source: https://github.com/color-js/color.js/blob/main/tests/conversions.html
Demonstrates conversions of out-of-gamut colors (e.g., rec2020) to HWB, HSL, and HSV color spaces. Shows how the library handles colors outside the standard sRGB gamut.
```javascript
convertToHWB();
```
```javascript
convertToHSL();
```
```javascript
convertToHSV();
```
--------------------------------
### Euclidean Distance in Perceptually Uniform Spaces
Source: https://github.com/color-js/color.js/blob/main/docs/color-difference.md
Shows how to calculate the Euclidean distance in perceptually uniform color spaces like Lab and Jzazbz for more accurate perceptual difference measurements.
```APIDOC
## Euclidean distance in perceptually uniform spaces
### Description
Calculates the Euclidean distance between two colors in perceptually uniform color spaces like Lab or Jzazbz.
### Method
`color1.distance(color2, "lab")` or `color1.distance(color2, "jzazbz")`
### Parameters
- **color2** (Color) - The second color to compare.
- **"lab"** or **"jzazbz"** (string) - Specifies the color space.
### Request Example
```js
let color1 = new Color("hsl(30, 100%, 50%)");
let color2 = new Color("hsl(50, 100%, 50%)");
color1.distance(color2, "lab");
color1.distance(color2, "jzazbz");
```
```
--------------------------------
### Compare Delta E Algorithms for Small Differences
Source: https://github.com/color-js/color.js/blob/main/docs/color-difference.md
Compare the results of Delta E 76, CMC, and 2000 for two very similar colors. This demonstrates how different algorithms can perceive small differences.
```javascript
let color1 = new Color("lch", [40, 50, 60]);
let color2 = new Color("lch", [43, 50, 60]);
color1.deltaE(color2, "76");
color1.deltaE(color2, "CMC");
color1.deltaE(color2, "2000");
```
--------------------------------
### Convert to OKLab
Source: https://github.com/color-js/color.js/blob/main/tests/conversions.html
Converts colors to the OKLab color space. This conversion is tested against published C++ code for accuracy.
```javascript
convertToOK();
```
--------------------------------
### Calculate Delta E using OK method
Source: https://github.com/color-js/color.js/blob/main/tests/delta.html
Use the OK method for Delta E calculations. This method is suitable for general color difference assessments and provides accurate results.
```javascript
deltaTest({method: "OK"});
```
--------------------------------
### Manually Convert to Supported CSS Color
Source: https://github.com/color-js/color.js/blob/main/docs/output.md
This snippet demonstrates a manual approach to convert a color to a CSS-supported format by checking browser support and falling back to sRGB if necessary. It's useful when you need fine-grained control over the conversion process.
```js
let green = new Color("lch", [80, 80, 120]);
let cssColor = green.toString();
if (!CSS.supports("color", cssColor))
cssColor = green.to("srgb").toString();
```
--------------------------------
### Index of Tests Display
Source: https://github.com/color-js/color.js/blob/main/test/index.html
If no test URL is provided, this logic fetches an 'index.json' file to list available tests. It then dynamically generates an HTML unordered list of links, each pointing to a specific test.
```javascript
else if (parent === self) {
document.documentElement.classList.add('index');
fetch('./index.json').then(r => r.json()).then(index => {
index = Object.entries(index).map(([id, name]) => ({ id, name }));
document.body.innerHTML = `
`;
});
}
```
--------------------------------
### Import Specific Color.js Modules
Source: https://github.com/color-js/color.js/blob/main/README.md
Import individual modules from Color.js's source directory for more granular control. This is useful for optimizing bundle size by only including necessary components.
```js
import Color from "https://colorjs.io/src/color.js";
import p3 from "https://colorjs.io/src/spaces/p3.js";
import rec2020 from "https://colorjs.io/src/spaces/rec2020.js";
import deltaE200 from "https://colorjs.io/src/deltaE/deltaE2000.js";
```
--------------------------------
### Benchmark culori with functional API
Source: https://github.com/color-js/color.js/blob/main/benchmarks/ai.html
Benchmarks the culori library for color creation, sRGB conversion, gamut checking, and serialization using its functional API. Requires a canvas element for rendering.
```javascript
import { displayable, rgb, formatRgb } from 'https://cdn.skypack.dev/culori';
test("culori", culori_canvas, {
create: (l, c, h) => ({mode: 'oklch', l, c, h}),
to_srgb: color => rgb(color),
in: color => displayable(color),
str: color => formatRgb(color)
});
```
--------------------------------
### Color Steps
Source: https://github.com/color-js/color.js/blob/main/docs/interpolation.md
Generate an array of discrete color steps between two colors using `color.steps()` and `Color.steps()`. Useful for creating gradients.
```APIDOC
## color.steps()
### Description
Generates an array of discrete color steps between the current color and a target color.
### Method
Instance method of a Color object.
### Parameters
- **otherColor** (Color | string) - The target color to generate steps towards.
- **options** (object, optional) - Configuration options for generating steps.
- **space** (string, optional) - The color space in which to perform interpolation. Defaults to 'lab'.
- **outputSpace** (string, optional) - The color space for the output colors. Defaults to the input color's space.
- **maxDeltaE** (number, optional) - The maximum Delta E between consecutive steps. Defaults to the deltaE76 function.
- **steps** (number, optional) - The minimum number of steps to generate.
### Request Example
```js
let color = new Color("p3", [0, 1, 0]);
color.steps("red", {
space: "lch",
outputSpace: "srgb",
maxDeltaE: 3, // max deltaE between consecutive steps (optional)
steps: 10 // min number of steps
});
```
## Color.steps()
### Description
Static method to generate an array of discrete color steps between two colors.
### Method
Static method of the Color class.
### Parameters
- **color1** (Color | string) - The starting color.
- **color2** (Color | string) - The ending color.
- **options** (object, optional) - Configuration options for generating steps. Same as `color.steps()`.
### Request Example
```js
Color.steps("red", "blue", { steps: 5 });
```
```
--------------------------------
### Mix Colors at Specific Proportions
Source: https://github.com/color-js/color.js/blob/main/docs/interpolation.md
The `color.mix()` method provides a shortcut for creating a color at a specific point within the interpolation range between two colors. Options for interpolation space and output space are available.
```javascript
let color = new Color("p3", [0, 1, 0]);
let redgreen = color.mix("red", .5, {space: "lch", outputSpace: "srgb"});
let reddishGreen = color.mix("red", .25, {space: "lch", outputSpace: "srgb"});
```
--------------------------------
### Calculate Delta E using Parameterized Syntax
Source: https://github.com/color-js/color.js/blob/main/docs/color-difference.md
Calculate various Delta E differences (76, CMC, 2000, ITP) using a parameterized syntax. This allows for flexibility in choosing the desired Delta E algorithm.
```javascript
let color1 = new Color("blue");
let color2 = new Color("lab", [30, 30, 30]);
let color3 = new Color("lch", [40, 50, 60]);
color1.deltaE(color2, "76");
Color.deltaE(color2, color3, "76");
color1.deltaE(color2, "CMC");
Color.deltaE(color2, color3, "CMC");
color1.deltaE(color2, "2000");
Color.deltaE(color2, color3, "2000");
color1.deltaE(color2, "ITP");
Color.deltaE(color2, color3, "ITP");
```
--------------------------------
### Modify Color Coordinates Using `set()` Method
Source: https://github.com/color-js/color.js/blob/main/README.md
Demonstrates using the `set()` method for relative and direct manipulation of multiple color coordinates. Supports functions for relative changes.
```javascript
let color = new Color("slategray");
// Multiple coordinates
color.set({
"lch.l": 80, // set lightness to 80
"lch.c": c => c * 1.2 // Relative manipulation
});
// Set single coordinate
color.set("hwb.w", w => w + 10);
```
--------------------------------
### Calculate Lightness Difference (Lstar)
Source: https://github.com/color-js/color.js/blob/main/docs/contrast.md
Calculate contrast using CIE Lightness L*, which is perceptually uniform, unlike luminance. This method is suitable for applications like Google Material Design's HCT Tone difference and automatically detects the lighter color.
```javascript
let color1 = new Color("p3", [0.9, 0.8, 0.1]);
let color2 = new Color("slategrey");
let contrast = color1.contrast(color2, "Lstar");
```
--------------------------------
### Calculate WCAG 2.1 Contrast
Source: https://github.com/color-js/color.js/blob/main/docs/contrast.md
Use this method to calculate the WCAG 2.1 contrast ratio between two colors. This is useful for accessibility checks, but note its limitations in dark mode and potential for false positives/negatives.
```javascript
let color1 = new Color("p3", [0.9, 0.8, 0.1]);
let color2 = new Color("slategrey");
let contrast = color1.contrast(color2, "WCAG21");
```
--------------------------------
### Create Color Object from Color Space and Coordinates
Source: https://github.com/color-js/color.js/blob/main/docs/the-color-object.md
Create a Color object by specifying the color space name and an array of its coordinates. Alpha is optional. Case-insensitivity and color space objects are supported.
```javascript
let lime = new Color("sRGB", [0, 1, 0], .5); // optional alpha
let yellow = new Color("P3", [1, 1, 0]);
new Color("lch", [50, 30, 180]);
// Capitalization doesn't matter
new Color("LCH", [50, 30, 180]);
// Color space objects work too
new Color(Color.spaces.lch, [50, 30, 180]);
```
--------------------------------
### Include Color.js as a Global Variable
Source: https://github.com/color-js/color.js/blob/main/README.md
Include Color.js via a script tag in your HTML to make the `Color` object globally available. This method is suitable for simpler projects or when not using module bundlers.
```html
```
--------------------------------
### WCAG 2.1 Contrast Calculation
Source: https://github.com/color-js/color.js/blob/main/docs/contrast.md
Calculates the WCAG 2.1 contrast ratio between two colors. This method is provided for compatibility and comparison, though it has known limitations.
```APIDOC
## WCAG 2.1 Contrast
### Description
Calculates the WCAG 2.1 contrast ratio between two colors. This method is provided for compatibility and comparison, though it has known limitations.
### Method
`contrast(color, algorithm)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Usage
```js
let color1 = new Color("p3", [0.9, 0.8, 0.1]);
let color2 = new Color("slategrey");
let contrast = color1.contrast(color2, "WCAG21");
```
### Response
#### Success Response (200)
- **contrast** (number) - The WCAG 2.1 contrast ratio between the two colors.
```
--------------------------------
### Watch and Process CSS Files
Source: https://github.com/color-js/color.js/blob/main/CONTRIBUTING.md
Monitors PostCSS source files and processes them, automatically rebuilding when changes are detected.
```bash
npm run watch:css
```
--------------------------------
### CAT02 Adaptation D65 to D50
Source: https://github.com/color-js/color.js/blob/main/tests/adapt.html
Tests the CAT02 chromatic adaptation from D65 to D50. Compares the output against a known matrix.
```javascript
$out(() => { let M = color_adapt(WHITES.D65, WHITES.D50, "CAT02"); return M; });
```
```javascript
$out(() => { return [ [ 1.0424827, 0.0308012, -0.0527444], [ 0.0221295, 1.0018823, -0.0210462], [-0.0011630, -0.0034170, 0.7620404] ]; });
```
--------------------------------
### Von Kries Adaptation A to C
Source: https://github.com/color-js/color.js/blob/main/tests/adapt.html
Tests the von Kries chromatic adaptation from Illuminant A to C. Compares the output against a published matrix.
```javascript
$out(() => { let M = color_adapt(WHITES.A, WHITES.C, "von Kries"); return M; });
```
```javascript
$out(() => { return [ [ 0.9418277, -0.2249131, 0.4806950], [-0.0247051, 1.0253682, 0.0049749], [ 0.0000000, 0.0000000, 3.3225235] ]; });
```
--------------------------------
### Test Gamut Mapping - JavaScript
Source: https://github.com/color-js/color.js/blob/main/tests/gamut.html
A helper function to test gamut mapping. It takes a target color space and optional arguments for the mapping method. Ensure the Color.js library is loaded.
```javascript
function gamutTest(toSpace, args) { let td = document.currentScript.parentNode.previousElementSibling; $out(() => { let color = new Color(td.textContent); let color2 = color.to(toSpace); return color2.toString({inGamut: args, precision: null}); }); }
```
--------------------------------
### Static Color Mixing
Source: https://github.com/color-js/color.js/blob/main/docs/interpolation.md
Use the static `Color.mix()` syntax for one-off color mixing operations without needing to instantiate a Color object first.
```javascript
Color.mix("color(display-p3 0 1 0)", "red", .5);
```
--------------------------------
### Create Color Object from Literal Object
Source: https://github.com/color-js/color.js/blob/main/docs/the-color-object.md
Instantiate a Color object using a literal object that specifies the color space, coordinates, and optionally alpha. Cloning an existing Color object is also supported.
```javascript
let red1 = new Color({space: "lab", coords: [50, 50, 50]});
let red2 = new Color({spaceId: "lab", coords: [50, 50, 50]});
let redClone = new Color(red1);
```
--------------------------------
### CAT02 Adaptation D50 to D65
Source: https://github.com/color-js/color.js/blob/main/tests/adapt.html
Tests the CAT02 chromatic adaptation from D50 to D65. Compares the output against a known matrix.
```javascript
$out(() => { let M = color_adapt(WHITES.D50, WHITES.D65, "CAT02"); return M; });
```
```javascript
$out(() => { return [ [ 0.9599435, -0.0292880, 0.0656334], [-0.0211745, 0.9988615, 0.0261212], [ 0.0013700, 0.0044344, 1.3124836] ]; });
```
--------------------------------
### CAT16 Adaptation C to D50
Source: https://github.com/color-js/color.js/blob/main/tests/adapt.html
Tests the CAT16 chromatic adaptation from Illuminant C to D50. Compares the output against a known matrix.
```javascript
$out(() => { let M = color_adapt(WHITES.C, WHITES.D50, "CAT16"); return M; });
```
```javascript
$out(() => { return [ [ 1.0059635, 0.0270676, -0.0418130], [ 0.0037323, 0.9940963, 0.0018973], [ 0.0004538, -0.0145289, 0.7098704] ]; });
```
--------------------------------
### CAT16 Adaptation D65 to D50
Source: https://github.com/color-js/color.js/blob/main/tests/adapt.html
Tests the CAT16 chromatic adaptation from D65 to D50. Compares the output against a known matrix.
```javascript
$out(() => { let M = color_adapt(WHITES.D65, WHITES.D50, "CAT16"); return M; });
```
```javascript
$out(() => { return [ [ 1.0108226, 0.0405991, -0.0341060], [ 0.0054139, 0.99359563, 0.0011560], [ 0.0002508, -0.01148016, 0.7682115] ]; });
```
--------------------------------
### Modify Color Coordinates Using Properties
Source: https://github.com/color-js/color.js/blob/main/README.md
Illustrates direct modification of color coordinates using object properties for different color spaces like LCH and HWB. Ensure the Color object is initialized.
```javascript
let color = new Color("slategray");
color.lch.l = 80; // Set coord directly in any color space
color.lch.c *= 1.2; // saturate by increasing LCH chroma by 20%
color.hwb.w += 10; // any other color space also available
```
--------------------------------
### CAT16 Adaptation D50 to D65
Source: https://github.com/color-js/color.js/blob/main/tests/adapt.html
Tests the CAT16 chromatic adaptation from D50 to D65. Compares the output against a known matrix.
```javascript
$out(() => { let M = color_adapt(WHITES.D50, WHITES.D65, "CAT16"); return M; });
```
```javascript
$out(() => { return [ [ 0.9894962, -0.0399233, 0.0439904], [-0.0053910, 1.0066456, -0.0017541], [-0.0004037, 0.0150564, 1.3016843] ]; });
```
--------------------------------
### Using Different Whitepoints with Bradford CAT
Source: https://github.com/color-js/color.js/blob/main/docs/adaptation.md
Demonstrates how the Bradford CAT is implicitly used when converting colors between spaces with different whitepoints (e.g., D65 to D50). No explicit CAT method needs to be called.
```javascript
let color1 = new Color("p3", [0.22, 0.63, 0.42]); // D65 white
let color2 = new Color("prophoto", [0.15, 0.54, 0.21]); //D50 white
color1.lch;
// linear Bradford was used to adapt to D50 before conversion to Lab
color2.lch;
// no CAT was needed, whitepoints the same
```
--------------------------------
### Benchmark Color.js with functional API
Source: https://github.com/color-js/color.js/blob/main/benchmarks/ai.html
Benchmarks the functional API of Color.js for color creation, sRGB conversion, gamut checking, and serialization. Requires a canvas element for rendering.
```javascript
function test(lib, canvas, f) { let ctx = canvas.getContext("2d"); let w = canvas.width; let i=0, j=0; let timeTaken = {create: 0, to_srgb: 0, in: 0, str: 0}; outerloop: for (let h = 0; h <= 360; h += 1) { for (let l = 0; l <= 1; l+=.05) { for (let c = 0; c <= 0.4; c+=.02) { let start; start = performance.now(); let color = f.create(l, c, h); timeTaken.create += performance.now() - start; start = performance.now(); let color_srgb = f.to_srgb(color); timeTaken.to_srgb += performance.now() - start; start = performance.now(); let inSRGB = f.in(color_srgb, color); timeTaken.in += performance.now() - start; let colorStr; if (inSRGB) { start = performance.now(); colorStr = f.str(color_srgb, color, inSRGB); timeTaken.str += performance.now() - start; } if (inSRGB) { ctx.fillStyle = colorStr; let x = i % w; let y = (i - x) / w; ctx.fillRect(x, y, 1, 1); i++; } j++; } } //console.log(`{${h}/360 done, taken ${timeTaken}ms so far}`); } let totalTime = timeTaken.create + timeTaken.to_srgb + timeTaken.in + timeTaken.str; console.log(`{lib}: {${i}/${j}} colors in gamut, took {totalTime}}ms ({timeTaken.create}}ms creation, {timeTaken.to_srgb}}ms conversion to srgb, {timeTaken.in}} in gamut check, {timeTaken.str}} serialization)`); }
```
```javascript
import Color from "../src/color.js";
import srgb from "../src/spaces/srgb.js";
import oklch from "../src/spaces/oklch.js";
// import to from "../src/to.js";
// import inGamut from "../src/inGamut.js";
// import serialize from "../src/serialize.js";
import {to, inGamut, serialize} from "../src/index-fn.js";
test("Color.js", colorjs_canvas, {
create: (l, c, h) => ({space: oklch, coords: [l, c, h]}),
to_srgb: color => to(color, srgb),
in: color_srgb => inGamut(color_srgb, srgb, {epsilon: 0}),
str: color_srgb => serialize(color_srgb)
});
```
--------------------------------
### Create Color from Object Literal
Source: https://github.com/color-js/color.js/blob/main/tests/construct.html
Instantiates a Color object using an object literal that specifies the color space and coordinates. Useful for programmatic color creation.
```javascript
$out(() => { var color = new Color({spaceId: "p3", coords: [0, 1, 0]}); return color.toJSON(); });
```
--------------------------------
### DeltaE 2000 Test: White to Black
Source: https://github.com/color-js/color.js/blob/main/tests/delta.html
Tests the DeltaE 2000 algorithm with white and black colors. Expects a DeltaE of 100.
```javascript
deltaTest({method: "2000"});
```
--------------------------------
### Bradford Adaptation A to C
Source: https://github.com/color-js/color.js/blob/main/tests/adapt.html
Tests the Bradford chromatic adaptation from Illuminant A to C. Compares the output against a published matrix.
```javascript
$out(() => { let M = color_adapt(WHITES.A, WHITES.C, "Bradford"); return M; });
```
```javascript
$out(() => { return [ [ 0.8530161, -0.1130268, 0.4404346], [-0.1238786, 1.0853435, 0.1425803], [ 0.0911907, -0.1553658, 3.4776250] ]; });
```
--------------------------------
### Setting Default DeltaE Algorithm
Source: https://github.com/color-js/color.js/blob/main/docs/color-difference.md
Allows changing the default DeltaE algorithm used by Color.js functions when no specific algorithm is provided.
```APIDOC
## Setting the default DeltaE algorithm
### Description
Changes the default DeltaE algorithm used by Color.js functions.
### Method
`Color.defaults.deltaE = "algorithm_name";`
### Parameters
- **"algorithm_name"** (string) - The desired default DeltaE algorithm (e.g., "2000").
### Request Example
```js
let color1 = new Color("blue");
let color2 = new Color("lch", [20, 50, 230]);
color1.deltaE(color2); // Uses default (e.g., DeltaE 1976)
Color.defaults.deltaE = "2000";
color1.deltaE(color2); // Now uses DeltaE 2000
```
```
--------------------------------
### Euclidean Distance in sRGB
Source: https://github.com/color-js/color.js/blob/main/docs/color-difference.md
Demonstrates calculating the Euclidean distance between two colors in the sRGB color space. Note that sRGB is not perceptually uniform, so this may not accurately reflect perceived differences.
```APIDOC
## Euclidean distance in sRGB
### Description
Calculates the Euclidean distance between two colors in the sRGB color space.
### Method
`color1.distance(color2, "srgb")`
### Parameters
- **color2** (Color) - The second color to compare.
- **"srgb"** (string) - Specifies the sRGB color space.
### Request Example
```js
let color1 = new Color("hsl(30, 100%, 50%)");
let color2 = new Color("hsl(50, 100%, 50%)");
color1.distance(color2, "srgb");
```
```
--------------------------------
### Static Color Mix Method
Source: https://github.com/color-js/color.js/blob/main/README.md
Uses the static mix method available on the Color class to mix two colors. This method accepts color strings as input.
```javascript
Color.mix("color(display-p3 0 1 0)", "red", .5);
```
--------------------------------
### Von Kries Adaptation C to D50
Source: https://github.com/color-js/color.js/blob/main/tests/adapt.html
Tests the von Kries chromatic adaptation from Illuminant C to D50. Compares the output against a published matrix.
```javascript
$out(() => { let M = color_adapt(WHITES.C, WHITES.D50, "von Kries"); return M; });
```
```javascript
$out(() => { return [ [ 1.0132609, 0.0457455, -0.0636638], [ 0.0050248, 0.9962695, -0.0010128], [ 0.0000000, 0.0000000, 0.6979583] ]; });
```
--------------------------------
### DeltaE 76 Test: White to Black
Source: https://github.com/color-js/color.js/blob/main/tests/delta.html
Tests the DeltaE 76 algorithm with white and black colors. Expects a DeltaE of 100.
```javascript
deltaTest();
```
--------------------------------
### WCAG 2.1 Contrast Calculation
Source: https://github.com/color-js/color.js/blob/main/tests/contrast.html
Calculates WCAG 2.1 contrast ratio for sRGB colors. Ensure colors are in sRGB.
```javascript
contrastTest("WCAG21");
```
--------------------------------
### Von Kries Adaptation F2 to D50
Source: https://github.com/color-js/color.js/blob/main/tests/adapt.html
Tests the von Kries chromatic adaptation from Illuminant F2 to D50. Compares the output against a published matrix.
```javascript
$out(() => { let M = color_adapt(WHITES.F2, WHITES.D50, "von Kries"); return M; });
```
```javascript
$out(() => { return [ [ 0.9869554, -0.0470220, 0.0479582], [-0.0051650, 1.0044210, 0.0010416], [ 0.0000000, 0.0000000, 1.2244744] ]; });
```
--------------------------------
### Create Color from P3 Array
Source: https://github.com/color-js/color.js/blob/main/tests/construct.html
Instantiates a Color object using the P3 color space with an array of coordinates. Use when defining colors in the P3 color space.
```javascript
$out(() => { var color = new Color("P3", [0, 1, 0]); return color.toJSON(); });
```
--------------------------------
### Convert ICtCp to REC2020
Source: https://github.com/color-js/color.js/blob/main/tests/conversions.html
Converts colors from the ICtCp color space back to REC2020. This is useful for reversing the previous conversion.
```javascript
color(ictcp 0.4413 -0.1164 0.3985)
convertToRec2020();
```
```javascript
color(ictcp 0.5305 -0.4247 -0.1219)
convertToRec2020();
```
```javascript
color(ictcp 0.3687 0.2746 -0.2406)
convertToRec2020();
```
--------------------------------
### Modifying Color Coordinates with `set()` and `setAll()`
Source: https://github.com/color-js/color.js/blob/main/docs/manipulation.md
Use the `set()` method for modifying multiple coordinates at once, supporting direct values or relative manipulations. The `setAll()` method is implicitly used when modifying multiple properties.
```javascript
let color = new Color("slategray");
// Multiple coordinates
color.set({
"lch.l": 80, // set lightness to 80
"lch.c": c => c * 1.2 // Relative manipulation
});
// Set single coordinate
color.set("hwb.w", w => w + 10);
```
```javascript
let color = new Color("slategray").to("lch");
// Multiple coordinates
color.set({
l: 80, // set lightness to 80
c: c => c * 1.2 // Relative manipulation
});
// Set single coordinate
color.set("h", 30);
```
--------------------------------
### Custom Format Definition
Source: https://github.com/color-js/color.js/blob/main/docs/output.md
Define and use entirely custom formats by providing a format object with a name and coordinate definitions.
```javascript
let lv_magenta = new Color("#ff0066");
lv_magenta.toString({
format: {
name: "myrgb",
coords: [
"[0, 255]",
"",
""
]
}
})
```
--------------------------------
### rec2100pq to XYZ and back
Source: https://github.com/color-js/color.js/blob/main/tests/conversions.html
Tests round-trip conversion between rec2100pq, XYZ, and Display P3 color spaces. Verifies accuracy for HDR color conversions.
```javascript
convertToXYZ();
```
```javascript
convertTo2100PQ();
```
--------------------------------
### Parameterized DeltaE Algorithms
Source: https://github.com/color-js/color.js/blob/main/docs/color-difference.md
Calculates DeltaE differences using various algorithms (CMC, 2000, ITP) by specifying the algorithm name as a string parameter.
```APIDOC
## Parameterized DeltaE Algorithms
### Description
Calculates DeltaE color differences using specified algorithms like CMC, 2000, or ITP.
### Method
`color1.deltaE(color2, "algorithm_name")` or `Color.deltaE(color1, color2, "algorithm_name")`
### Parameters
- **color2** (Color) - The second color to compare.
- **"algorithm_name"** (string) - The DeltaE algorithm to use (e.g., "CMC", "2000", "ITP").
### Request Example
```js
let color1 = new Color("blue");
let color2 = new Color("lab", [30, 30, 30]);
color1.deltaE(color2, "CMC");
Color.deltaE(color2, color1, "2000");
color1.deltaE(color2, "ITP");
```
```
--------------------------------
### Mix Colors at a Specific Point
Source: https://github.com/color-js/color.js/blob/main/README.md
Mixes two colors at a specified percentage, allowing for custom interpolation and output color spaces. This provides a shortcut for specific points in a range.
```javascript
let color = new Color("p3", [0, 1, 0]);
let redgreen = color.mix("red", .5, {space: "lch", outputSpace: "srgb"});
let reddishGreen = color.mix("red", .25, {space: "lch", outputSpace: "srgb"});
```
--------------------------------
### Create Color from HSL String
Source: https://github.com/color-js/color.js/blob/main/tests/construct.html
Instantiates a Color object from a HSL color string. This constructor parses the HSL string and converts it to an internal representation.
```javascript
$out(() => { return new Color("hsl(10, 50%, 50%)").toJSON(); });
```
--------------------------------
### Stringify Color in Different Spaces
Source: https://github.com/color-js/color.js/blob/main/README.md
Outputs a color in its default string format or a specified format with precision. The default stringification uses the '+' operator or toString().
```javascript
let color = new Color("slategray");
color + ""; // default stringification
color.to("p3").toString({precision: 3});
```
--------------------------------
### Custom HEX Output
Source: https://github.com/color-js/color.js/blob/main/docs/output.md
Customize HEX output by controlling options like 'collapse'.
```javascript
let lv_magenta = new Color("#ff0066");
lv_magenta.toString({format: "hex"});
lv_magenta.toString({format: "hex", collapse: false});
```
--------------------------------
### Von Kries Chromatic Adaptation Transform
Source: https://github.com/color-js/color.js/blob/main/docs/adaptation.md
Illustrates the von Kries method for chromatic adaptation. This transform converts colors to cone responses, scales them based on illuminant differences, and converts back to XYZ, offering better accuracy than XYZ scaling for similar illuminants and less saturated colors.
```javascript
let W1 = Color.WHITES.D65;
let W2 = Color.WHITES.D50;
let color = new Color("rebeccapurple");
// now get the xyz-d65 coordinates
// and matrix multiply by a cone response matrix
// scale by the whites
// and convert back to XYZ with a new white point.
```
--------------------------------
### Chaining Color Modifications
Source: https://github.com/color-js/color.js/blob/main/docs/manipulation.md
Perform sequential color manipulations using chaining style, combining `set()` with other methods like `lighten()` for fluent updates.
```javascript
let color = new Color("lch(50% 50 10)");
color = color.set({
h: h => h + 180,
c: 60
}).lighten();
```
--------------------------------
### Generate Color Steps
Source: https://github.com/color-js/color.js/blob/main/README.md
Calculates discrete steps between two colors, controlling the interpolation space, output space, maximum Delta E, and minimum number of steps.
```javascript
let color = new Color("p3", [0, 1, 0]);
color.steps("red", {
space: "lch",
outputSpace: "srgb",
maxDeltaE: 3, // max deltaE between consecutive steps
steps: 10 // min number of steps
});
```