Color.js

repository·main·Indexed 25 days ago

https://github.com/color-js/color.js

A professional-grade color conversion and modification library supporting CSS Color 4, various color spaces (Lab, OKLab, P3, etc.), and advanced gamut mapping. It provides tools for manipulating color coordinates, interpolating between colors, calculating Euclidean and Delta E (ΔE) perceptual distances, and measuring contrast using algorithms such as WCAG21, APCA, and Weber. The library also handles automatic chromatic adaptation using the linear Bradford transform when converting between different whitepoints.

Tokens
20.2K
Snippets
40
Records
128
Agent score
80%

What's inside colorjs.io

  1. How to control hue interpolation in color spaces

    main

    When interpolating in color spaces that use a hue angle (like lch, hsl, or hwb), you can specify how the hue transition is handled using the hue option. This prevents unexpected color shifts. The available values are:

    • shorter (default): Takes the shortest path around the hue circle.
    • longer: Takes the long way around the hue circle.
    • increasing: Increases the hue angle.
    • decreasing: Decreases the hue angle.
    • raw: Uses the raw numerical values without circular logic.
    let c1 = new Color("rebeccapurple");
    let c2 = new Color("lch", [85, 85, 85 + 720]);
    
    c1.range(c2, {space: "lch", hue: "longer"});
    c1.range(c2, {space: "lch", hue: "shorter"});
    c1.range(c2, {space: "lch", hue: "increasing"});
    c1.range(c2, {space: "lch", hue: "decreasing"});
    c1.range(c2, {space: "lch", hue: "raw"});
  2. Handle achromatic transitions and transparency using NaN

    main

    In Color.js, interpolating between a coordinate and NaN keeps that coordinate constant. This is a powerful way to handle achromatic transitions (e.g., fading to white or black) or fading to transparency without affecting other channels.

    To fade to transparent, you can interpolate towards a color with NaN coordinates or use the transparent keyword.

  3. Understand Chromatic Adaptation in Color.js

    main

    Chromatic adaptation is the process by which colors are predicted to look the same under different illuminants (light sources). In Color.js, this is handled via Chromatic Adaptation Transforms (CATs).

    When you convert a color between colorspaces that use different whitepoints (e.g., converting from an sRGB color which uses D65 to an LCH color which uses D50), Color.js automatically applies a chromatic adaptation transform to ensure the color remains perceptually consistent.

  4. How Bradford CAT works as the default transform

    main

    The Bradford transform is the default Chromatic Adaptation Transform (CAT) used by Color.js. It uses a simplified, linear version of the Bradford method, which is the standard required by ICC color profiles.

    This transform is applied automatically during conversions between colorspaces with different whitepoints. For example, if you convert a color from sRGB or display-P3 (D65 whitepoint) to LCH (D50 whitepoint), the XYZ values are passed through a linear Bradford CAT before being converted to Lab and LCH.

  5. Create a CSS gradient from a color range

    main

    To visualize a color range (created via Color.range()) as a CSS gradient, use Color.steps() to generate a sequence of color stops.

    Implementation Steps

    1. Define a range using Color.range(start, end).
    2. Generate steps using Color.steps(range, options).
      • steps: The number of color stops to generate.
      • maxDeltaE: The maximum allowed Delta E (perceptual difference) between consecutive colors. If this is set, the method may generate more steps than requested to ensure perceptual smoothness.
    3. Join the resulting colors into a string for the CSS linear-gradient property.

    Best Practice: Use .display() on each step when mapping to strings to ensure the gradient stops are browser-compatible.

    let r = Color.range("rebeccapurple", "gold");
    let stops = Color.steps(r, {steps: 10});
    
    // Apply to an element
    element.style.background = `linear-gradient(to right, ${stops.map(c => c.display()).join(", ")})`;
    let r = Color.range("hsl(330 90% 50%)", "hotpink");
    let stops = Color.steps(r, {steps: 5, maxDeltaE: 3});
    let element = document.querySelector("#test");
    element.style.background = `linear-gradient(to right, ${stops.join(", ")})`;
  6. Install colorjs.io

    main

    You can install Color.js using several methods depending on your environment:

    npm

    For standard Node.js or bundler-based projects:

    npm install colorjs.io

    CDN (ES Modules)

    For quick experiments in the browser, import directly from esm.sh:

    import Color from "https://esm.sh/colorjs.io";

    Global Variable

    To use a global Color variable in HTML, include the following script:

    <script src="https://colorjs.io/dist/color.global.js"></script>

    Modular Imports

    To reduce bundle size, you can import specific modules directly from the src directory via npm or CDN:

    • NPM: node_modules/colorjs.io/src/
    • CDN: https://colorjs.io/src/

    Note: When using import in a browser, your <script> must have type="module".

  7. Use the procedural, tree-shakeable API

    main

    Color.js provides a procedural API that operates on plain objects instead of Color class instances. This API is approximately twice as fast as the object-oriented API and is tree-shakeable, which helps reduce bundle sizes when using modern build tools.

    To use this API, import functions directly from the colorjs.io/fn module. Note that you must manually register color spaces using ColorSpace.register() to enable parsing and conversion for those spaces.

    import {
    	to as convert,
    	toGamut,
    	serialize,
    	ColorSpace,
    	sRGB,
    	P3,
    	LCH
    } from "colorjs.io/fn";
    
    // Register color spaces for parsing and converting
    ColorSpace.register(sRGB);
    ColorSpace.register(P3);
    ColorSpace.register(LCH);
    
    // 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);
  8. Manipulate color coordinates directly

    main

    You can modify a color by directly accessing and assigning values to its color space properties. You can target any supported color space (e.g., lch, hwb, oklch) using the property path. This allows for both absolute assignment and relative manipulation using arithmetic operators.

    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
  9. Optimize performance for color operations

    main

    When performing performance-sensitive tasks where every millisecond counts, follow these two patterns:

    1. Use the Procedural API: Use functions from colorjs.io/fn operating on plain objects instead of the Color class.
    2. Avoid String Parsing for Coordinates: For functions that accept a coordinate reference (like get(color, coord) or set(color, coord, value)), pass the reference as an array or an object instead of a string. This avoids the overhead of parsing the string at runtime.

    Recommended formats for coordinate references:

    • Array: [ColorSpace.get("lch"), "l"]
    • Object: {space: ColorSpace.get("lch"), coordId: 'l'}
  10. Use the Okhsl color space

    main

    Okhsl is a color space implementation in Color.js that provides a perceptually uniform representation of color using Hue (h), Saturation (s), and Lightness (l). It is based on the Oklab color space and is designed to have a more intuitive lightness and saturation model.

    Coordinates:

    • Hue (h): An angle from 0 to 360.
    • Saturation (s): A value from 0 to 1.
    • Lightness (l): A value from 0 to 1.

    Okhsl can be used as a base color space or via the okhsl-prism gamut space, which maps Okhsl values to the HSL color space.

  11. Create and manage color spaces with ColorSpace

    main

    The ColorSpace class is the core abstraction for defining and managing color spaces in Color.js. It handles coordinate metadata, white points, gamut checking, and color space conversions. You can create custom color spaces by providing an options object to the constructor, or use the built-in spaces via ColorSpace.get().

    Key capabilities include:

    • Conversion: Move coordinates between spaces using .to(space, coords) or .from(space, coords).
    • Gamut Checking: Verify if coordinates are within a space's gamut using .inGamut(coords).
    • Registry: Register and retrieve color spaces by ID using ColorSpace.register() and ColorSpace.get().
    • Coordinate Resolution: Resolve coordinate references (absolute or relative) using ColorSpace.resolveCoord().

    Note: For built-in color spaces, use ColorSpace.get('space-id') instead of manual instantiation.

  12. Available feature sets on the Color class

    main

    The Color class is extended with several functional modules. While the specific method names are defined in their respective files, the following categories of functionality are attached to the Color class:

    • Color Spaces: Full support for all color spaces.
    • DeltaE: Methods for calculating color difference (including deltaE and deltaEMethods).
    • Variations: Color variation utilities.
    • Contrast: Accessibility-related contrast calculations.
    • Chromaticity: Chromaticity-related calculations.
    • Luminance: Luminance and lightness calculations.
    • Interpolation: Color interpolation algorithms.
    • Contrast Methods: Advanced contrast calculation methods.