5.6.38 • Published 22 hours ago

@thi.ng/color v5.6.38

Weekly downloads
366
License
Apache-2.0
Repository
github
Last release
22 hours ago

color

npm version npm downloads Twitter Follow

This project is part of the @thi.ng/umbrella monorepo.

For the Clojure version, please visit: thi.ng/color-clj

About

Array-based color types, CSS parsing, conversions, transformations, declarative theme generation, gradients, presets.


Note: Version 3.0.0 constitutes an almost complete overhaul of the entire package, providing a more simple and flexible API, as well as various new additional features (compared to previous versions).


Supported color spaces / modes

Fast color model/space conversions (any direction) between (in alphabetical order). All types support an alpha channel, which defaults to 100% opaque (apart from the integer types).

  • ABGR (uint32, 0xaabbggrr, aka sRGB(A) as packed int)
  • ARGB (uint32, 0xaarrggbb, aka sRGB(A) as packed int)
  • CSS (string, hex3/4/6/8, named colors, system colors, rgba(), hsla(), lch(), lab(), etc.)
  • HCY (float4, similar to LCH)
  • HSI (float4)
  • HSL (float4)
  • HSV (float4)
  • Lab (float4, D50/D65 versions)
  • LCH (float4)
  • Oklab (float4)
  • RGB (float4, linear)
  • sRGB (float4, gamma corrected)
  • XYY (float4)
  • XYZ (float4, aka CIE 1931, D50/D65 versions)
  • YCC (float4, aka YCbCr)
From/ToCSSHCYHSIHSLHSVIntLabLCHOklabRGBsRGBXYYXYZYCC
CSS🆎🆎🆎(1)(4)🆎🆎🆎🆎
HCY🆎🆎🆎🆎🆎🆎🆎(2)(2)🆎🆎🆎
HSI🆎🆎🆎🆎🆎🆎🆎(2)(2)🆎🆎🆎
HSL🆎🆎🆎🆎🆎🆎(2)(2)🆎🆎🆎
HSV🆎🆎🆎🆎🆎🆎(2)(2)🆎🆎🆎
Int🆎🆎🆎🆎🆎🆎🆎🆎🆎🆎
Lab🆎🆎🆎🆎(3)🆎(3)🆎🆎(3)🆎
LCH🆎🆎🆎🆎🆎🆎🆎🆎🆎🆎
Oklab🆎🆎🆎🆎🆎🆎🆎🆎🆎🆎
RGB🆎(2)(2)(2)(2)(3)🆎(3)(2)
sRGB(2)(2)(2)(2)🆎🆎🆎🆎🆎🆎
XYY🆎🆎🆎🆎🆎🆎🆎🆎🆎🆎🆎
XYZ🆎🆎🆎🆎🆎🆎🆎🆎(3)🆎
YCC🆎🆎🆎🆎🆎🆎🆎🆎(2)🆎🆎🆎
  • ✅ - direct conversion
  • 🆎 - indirect conversion (mostly via RGB/sRGB)
  • (1) - only via parseHex()
  • (2) - no consideration for linear/gamma encoded RGB/sRGB (see Wikipedia)
  • (3) - including D50/D65 illuminant options
  • (4) - parsed as Lab w/ D50 illuminant as per CSS Color Module Level 4

Color creation / conversion

Each color type provides a factory function to create & convert color instances from other models/spaces. These functions can take the following arguments:

  • CSS string
  • number (interpreted as packed ARGB int32)
  • array (used as is)
  • scalars (one per channel, alpha optional, always defaults to 1.0)
  • color instance (triggers conversion)

Additionally, an optional target backing buffer, start index and stride can be given. See next section.

Some examples:

srgb("#ff0")
// $Color { offset: 0, stride: 1, buf: [ 1, 1, 0, 1 ] }

srgb(0x44ffff00)
// $Color { offset: 0, stride: 1, buf: [ 1, 1, 0, 0.26666666666666666 ] }

srgb(1,1,0)
// $Color { offset: 0, stride: 1, buf: [ 1, 1, 0, 1 ] }

srgb([0.1, 0.2, 0.3, 0.4])
// $Color { offset: 0, stride: 1, buf: [ 0.1, 0.2, 0.3, 0.4 ] }

// convert RGB CSS into Lab (D50)
labD50("#ff0")
// $Color {
//   offset: 0,
//   stride: 1,
//   buf: [ 0.9760712516622824, -0.1575287517691254, 0.9338847788323792, 1 ]
// }

// convert RGB CSS into Lab CSS (CSS Level 4 only)
css(labD50("#ff0"))
// 'lab(97.607% -15.753 93.388)'

// round trip:
// CSS -> sRGB -> lin RGB -> Lab -> lin RGB -> sRGB -> CSS
css(rgb(labD50("#ff0")))
// '#ffff00'

Additionally, colors can be created from black body temperatures (kelvinRgb()) or wavelengths (wavelengthXyz()).

kelvinRgb() result swatches

wavelengthXyz() result swatches

Storage & memory mapping

All color types store their channel values in plain arrays, typed arrays of (mostly) normalized values ([0,1] interval). Where applicable, the hue too is stored in that range (similar to CSS turn units), NOT in degrees. Likewise, luminance is always stored in the [0,1] too, even for Lab, LCH where often the [0,100] range is used instead.

As a fairly unique feature, all color types can be used to provided views of a backing memory buffer (e.g. for WASM/WebGL/WebGPU interop, pixel buffers etc.), incl. support for arbitrary component strides.

The lightweight class wrappers act similarly to the Vec2/3/4 wrappers in @thi.ng/vectors, support striding (for mapped memory views), named channel accessor aliases (in addition to array indexing) and are fully compatible with all vector functions.

Memory diagram of densely packed buffer

const memory = new Float32Array(16);

// create RGBA color views of buffer: num, start index, strides
// here the colors are tightly packed w/o gaps in between
// (by default entire buffer is mapped, last 4 args are optional)
const colors = rgb.mapBuffer(memory, 4, 0, 1, 4);

// manipulating the colors, will directly manipulate the underlying buffer
namedHueRgb(colors[0], Hue.ORANGE);
namedHueRgb(colors[1], Hue.CHARTREUSE);
namedHueRgb(colors[2], Hue.SPRING_GREEN);
namedHueRgb(colors[3], Hue.AZURE);

memory
// Float32Array(16) [ 1, 0.5, 0, 1, 0.5, 1, 0, 1, 0, 1, 0.5, 1, 0, 0.5, 1, 1 ]

css(colors[0])
// '#ff8000'
css(colors[1])
// '#80ff00'
css(colors[2])
// '#00ff80'
css(colors[3])
// '#0080ff'

// use deref() to obtain a packed copy
colors[0].deref()
// [ 1, 0.5, 0, 1 ]

Memory diagram of strided & interleaved buffer

// here we create a *strided* WebGL attrib buffer for 3 points
// each point defines a: 3D position, UV coords and RGB(A) color
const attribs = new Float32Array([
  // pos     uv   color
  0,0,0,     0,0, 0.25,0.5,0,1,
  100,0,0,   1,0, 0.5,0.5,0.25,1,
  100,100,0, 1,1, 0,1,0.5,1,
]);

// create strided view of colors
// 3 items, start index 5, component stride 1, element stride 9
colors = srgb.mapBuffer(attribs, 3, 5, 1, 9);

css(colors[0])
// '#408000'
css(colors[1])
// '#808040'
css(colors[2])
// '#00ff80'

Color theme generation

The package provides several methods for declarative & probabilistic color theme generation. The latter relies on the concept of LCH color ranges, which can be sampled directly and/or mixed with a base color (of any type) to produce randomized variations. Furthermore, multiple such ranges can be combined into a weighted set to define probabilistic color themes.

// single random color drawn from the "bright" color range preset
colorFromRange("bright");
// [ 0.7302125322518669, 0.8519945301256682, 0.8134374983367859, 1 ]

// single random color based on given raw HSV base color and preset
colorFromRange("warm", { base: hsv(0.33, 1, 1) })
// $Color {
//   offset: 0,
//   stride: 1,
//   buf: [ 0.774977122048776, 0.7432832945738063, 0.3186095419992927, 1 ]
// }

// infinite iterator of colors sampled from the preset
// (see table below)
const colors = colorsFromRange("bright");
colors.next();
// {
//   value: [ 0.006959075656347791, 0.8760165887192115, 0.912149937028727, 1 ],
//   done: false
// }

// 10 cool reds, w/ ±10% hue variance
[...colorsFromRange("cool", { num: 10, base: lch(1, 0.8, 0), variance: 0.1 })]

// generate colors based on given (weighted) textual description(s)
// here using named CSS colors, but could also be or typed colors or raw LCH tuples
[...colorsFromTheme(
    [["warm", "goldenrod"], ["cool", "springgreen", 0.1]],
    { num: 100, variance: 0.05 }
)]

// theme parts can also be given in the format used internally
// all keys are optional (range, base, weight),
// but at least `range` or `base` must be given...
[...colorsFromTheme(
    [
        { range: "warm", base: "goldenrod" },
        { range: COLOR_RANGES.cool, base: hsv(0, 1, 0.5), weight: 0.1 }
    ],
    { num: 100, variance: 0.05 }
)]

This table below shows three sets of sample swatches for each color range preset and the following color theme (raw samples and chunked & sorted):

  • 1/3 goldenrod
  • 1/3 turquoise
  • 1/3 pink
  • 1/6 black
  • 1/6 gray
  • 1/6 white
ID100 colors drawn from color range preset
brightcolor swatches
color swatches
color swatches
coolcolor swatches
color swatches
color swatches
darkcolor swatches
color swatches
color swatches
freshcolor swatches
color swatches
color swatches
hardcolor swatches
color swatches
color swatches
intensecolor swatches
color swatches
color swatches
lightcolor swatches
color swatches
color swatches
neutralcolor swatches
color swatches
color swatches
softcolor swatches
color swatches
color swatches
warmcolor swatches
color swatches
color swatches
weakcolor swatches
color swatches
color swatches

Full example:

import { colorsFromTheme, swatchesH } from "@thi.ng/color";
import { serialize } from "@thi.ng/hiccup";
import { svg } from "@thi.ng/hiccup-svg";
import { writeFileSync } from "fs";

// color theme definition using:
// color range preset names, CSS colors and weights
const theme: ColorThemePartTuple[] = [
    ["cool", "goldenrod"],
    ["hard", "hotpink", 0.1],
    ["fresh", "springgreen", 0.1],
];

// generate 200 LCH colors based on above description
const colors = [...colorsFromTheme(theme, { num: 200, variance: 0.05 })];

// create SVG doc of color swatches (hiccup format)
const doc = svg(
    { width: 1000, height: 50, convert: true },
    swatchesH(colors, 5, 50)
);

// serialize to SVG file
writeFileSync("export/swatches-ex01.svg", serialize(doc));

example result color swatches

Color sorting & distance

The package provides several functions to compute full or channel-wise distances between colors. These functions can also be used for sorting color arrays (see below).

  • distChannel - single channel distance only
  • distHsv / distHsvSat / distHsvLuma
  • distEucledian3 / distEucledian4
  • distRgbLuma / distSrgbLuma
  • distCIEDE2000
  • distCMC

The sort() function can be used to sort an array of colors using arbitrary sort criteria (basically any function which can transform a color into a number). The following comparators are bundled:

  • selectChannel(i) - sort by channel
  • proximity(target, distFn) - sort by distance to target color using given distance function
  • luminance / luminanceRgb / luminanceSrgb etc.
// (see above example)
const colors = [...colorsFromTheme(theme, { num: 200, variance: 0.05 })];

sortColors(colors, proximity(lch("#fff"), distCIEDE2000()));

sorted color swatches

Sorting memory-mapped colors

Memory mapped colors (e.g. a mapped pixel buffer) can be sorted (in place) via sortMapped(). This function does NOT change the order of elements in the given colors array, BUT instead sorts the apparent order by swapping the contents of the backing memory.

See the pixel sorting example for a concrete use case...

// memory buffer of 4 sRGB colors
const buf = new Float32Array([0,1,0,1, 0,0.5,0,1, 0,0.25,0,1, 0,0.75,0,1]);

// map buffer (creates 4 SRGB instances linked to the buffer)
const pix = srgb.mapBuffer(buf);

// display original order
pix.map(css);
// [ '#00ff00', '#008000', '#004000', '#00bf00' ]

// sort colors (buffer!) by luminance
sortMapped(pix, luminanceSrgb);

// new order
pix.map(css);
// [ '#004000', '#008000', '#00bf00', '#00ff00' ]

// buffer contents have been re-ordered
buf
// Float32Array(16) [
//     0, 0.25, 0, 1,    0,
//   0.5,    0, 1, 0, 0.75,
//     0,    1, 0, 1,    0,
//     1
// ]

Gradients

Multi-stop gradients in any color space

The multiColorGradient() function can be used to generate gradients in any color space and gradient stops must be using all the same color type. Colors are pairwise interpolated, and by default, uses generic mix() function which delegates to type specific strategies. See GradientOpts for details.

LCH example gradient

const L = 0.8;
const C = 0.8;

const gradient = multiColorGradient({
    num: 100,
    // gradient stops
    stops: [
        [0, lch(L, C, 0)],
        [1 / 3, lch(L, C, 1 / 3)],
        [2 / 3, lch(L, C, 2 / 3)],
        [1, lch(L, 0, 1)],
    ],
    // optionally with easing function
    // easing: (t) => t * t,
});

writeFileSync(
    `export/lch-gradient.svg`,
    serialize(
        svg(
            { width: 500, height: 50, convert: true },
            swatchesH(gradient, 5, 50)
        )
    )
);

Cosine gradients

The following presets are bundled (in cosine-gradients.ts):

PreviewGradient ID
gradient: blue-cyanblue-cyan
gradient: blue-magenta-orangeblue-magenta-orange
gradient: blue-white-redblue-white-red
gradient: cyan-magentacyan-magenta
gradient: green-blue-orangegreen-blue-orange
gradient: green-cyangreen-cyan
gradient: green-magentagreen-magenta
gradient: green-redgreen-red
gradient: heat1heat1
gradient: magenta-greenmagenta-green
gradient: orange-blueorange-blue
gradient: orange-magenta-blueorange-magenta-blue
gradient: purple-orange-cyanpurple-orange-cyan
gradient: rainbow1rainbow1
gradient: rainbow2rainbow2
gradient: rainbow3rainbow3
gradient: rainbow4rainbow4
gradient: red-bluered-blue
gradient: yellow-green-blueyellow-green-blue
gradient: yellow-magenta-cyanyellow-magenta-cyan
gradient: yellow-purple-magentayellow-purple-magenta
gradient: yellow-redyellow-red
Two-color cosine gradients

The cosineCoeffs() function can be used to compute the cosine gradient coefficients between 2 start/end colors:

// compute gradient coeffs between red / green
cosineGradient(10, cosineCoeffs([1,0,1,1], [0,1,0,1])).map(css)
// '#ff00ff'
// '#f708f7'
// '#e11ee1'
// '#bf40bf'
// '#966996'
// '#699669'
// '#40bf40'
// '#1ee11e'
// '#08f708'
// '#00ff00'
Multi-stop gradients

The multiCosineGradient() function returns an iterator of raw RGB colors based on given gradient stops. This iterator computes a cosine gradient between each color stop and yields a sequence of RGB values.

multiCosineGradient({
    num: 10,
    // gradient stops (normalized positions)
    stops: [[0.1, [1, 0, 0, 1]], [0.5, [0, 1, 0, 1]], [0.9, [0, 0, 1, 1]]],
    // optional color transform/coercion
    tx: srgba
})
// convert to CSS
.map(css)
// [
//   "#ff0000",
//   "#ff0000",
//   "#da2500",
//   "#807f00",
//   "#25da00",
//   "#00ff00",
//   "#00da25",
//   "#00807f",
//   "#0025da",
//   "#0000ff",
//   "#0000ff",
// ]

RGB color transformations

RGB color matrix transformations, including parametric preset transforms:

  • brightness
  • contrast
  • exposure
  • saturation (luminance aware)
  • hue rotation
  • color temperature (warm / cold)
  • sepia (w/ fade amount)
  • tint (green / magenta)
  • grayscale (luminance aware)
  • subtraction/inversion (also available as non-matrix op)
  • luminance to alpha

Transformation matrices can be combined using matrix multiplication / concatenation (see concat()) for more efficient application.

Status

STABLE - used in production

Search or submit any issues for this package

Support packages

Related packages

  • @thi.ng/pixel - Typedarray integer & float pixel buffers w/ customizable formats, blitting, drawing, convolution
  • @thi.ng/vectors - Optimized 2d/3d/4d and arbitrary length vector operations

Installation

yarn add @thi.ng/color

ES module import:

<script type="module" src="https://cdn.skypack.dev/@thi.ng/color"></script>

Skypack documentation

For Node.js REPL:

# with flag only for < v16
node --experimental-repl-await

> const color = await import("@thi.ng/color");

Package sizes (gzipped, pre-treeshake): ESM: 14.19 KB

Dependencies

Usage examples

Several demos in this repo's /examples directory are using this package.

A selection:

ScreenshotDescriptionLive demoSource
Probabilistic color theme generatorDemoSource
Heatmap visualization of this mono-repo's commitsSource
Color palette generation via dominant color extraction from uploaded imagesDemoSource
Visualization of different grid iterator strategiesDemoSource
Various hdom-canvas shape drawing examples & SVG conversion / exportDemoSource
Image dithering and remapping using indexed palettesDemoSource
Interactive pixel sorting tool using thi.ng/color & thi.ng/pixelDemoSource
Fork-join worker-based raymarch renderer (JS/CPU only)DemoSource

API

Generated API docs

Authors

Karsten Schmidt

If this project contributes to an academic publication, please cite it as:

@misc{thing-color,
  title = "@thi.ng/color",
  author = "Karsten Schmidt",
  note = "https://thi.ng/color",
  year = 2016
}

License

© 2016 - 2021 Karsten Schmidt // Apache Software License 2.0

5.6.38

22 hours ago

5.6.37

2 days ago

5.6.36

7 days ago

5.6.35

8 days ago

5.6.34

11 days ago

5.6.33

12 days ago

5.6.32

16 days ago

5.6.31

20 days ago

5.6.30

20 days ago

5.6.29

22 days ago

5.6.28

27 days ago

5.6.27

28 days ago

5.6.26

30 days ago

5.6.25

1 month ago

5.6.22

1 month ago

5.6.24

1 month ago

5.6.23

1 month ago

5.6.20

1 month ago

5.6.21

1 month ago

5.6.19

1 month ago

5.6.18

2 months ago

5.6.17

2 months ago

5.6.15

2 months ago

5.6.14

2 months ago

5.6.16

2 months ago

5.6.13

2 months ago

5.6.12

2 months ago

5.6.11

2 months ago

5.6.10

3 months ago

5.6.9

3 months ago

5.6.8

3 months ago

5.6.7

3 months ago

5.6.6

3 months ago

5.6.5

4 months ago

5.6.4

4 months ago

5.6.3

4 months ago

5.6.2

4 months ago

5.5.30

5 months ago

5.5.31

5 months ago

5.5.28

5 months ago

5.5.29

5 months ago

5.5.26

5 months ago

5.5.27

5 months ago

5.5.24

5 months ago

5.5.25

5 months ago

5.5.22

6 months ago

5.5.23

5 months ago

5.5.20

6 months ago

5.5.21

6 months ago

5.5.19

6 months ago

5.5.17

7 months ago

5.5.18

7 months ago

5.5.15

7 months ago

5.5.16

7 months ago

5.5.13

7 months ago

5.5.14

7 months ago

5.5.11

8 months ago

5.5.12

7 months ago

5.5.10

8 months ago

5.5.9

8 months ago

5.5.8

8 months ago

5.5.7

8 months ago

5.5.6

8 months ago

5.5.5

9 months ago

5.6.1

4 months ago

5.6.0

5 months ago

5.5.4

10 months ago

5.5.3

10 months ago

5.5.2

11 months ago

5.5.1

11 months ago

5.5.0

11 months ago

5.4.7

12 months ago

5.4.6

1 year ago

5.4.5

1 year ago

5.4.4

1 year ago

5.4.3

1 year ago

5.4.2

1 year ago

5.3.3

1 year ago

5.4.1

1 year ago

5.4.0

1 year ago

5.3.2

1 year ago

5.3.1

1 year ago

5.3.0

1 year ago

5.2.18

1 year ago

5.2.17

1 year ago

5.2.16

1 year ago

5.2.15

1 year ago

5.2.14

1 year ago

5.2.13

1 year ago

5.2.12

1 year ago

5.2.11

1 year ago

5.2.10

1 year ago

5.2.9

1 year ago

5.2.8

1 year ago

5.2.7

1 year ago

5.2.6

1 year ago

5.2.5

1 year ago

5.2.4

1 year ago

5.2.3

1 year ago

5.2.2

1 year ago

5.2.1

2 years ago

5.2.0

2 years ago

5.1.11

2 years ago

5.1.9

2 years ago

5.1.8

2 years ago

5.1.7

2 years ago

5.1.6

2 years ago

5.1.5

2 years ago

5.1.4

2 years ago

5.1.3

2 years ago

5.1.2

2 years ago

5.1.10

2 years ago

5.0.4

2 years ago

5.0.3

2 years ago

5.0.2

2 years ago

5.1.1

2 years ago

5.1.0

2 years ago

5.0.1

2 years ago

5.0.0

2 years ago

4.1.7

2 years ago

4.0.9

2 years ago

4.1.4

2 years ago

4.1.3

2 years ago

4.1.6

2 years ago

4.1.5

2 years ago

4.1.0

2 years ago

4.1.2

2 years ago

4.1.1

2 years ago

4.0.7

2 years ago

4.0.8

2 years ago

4.0.4

2 years ago

4.0.6

2 years ago

4.0.1

2 years ago

4.0.0

2 years ago

4.0.3

2 years ago

3.2.7

3 years ago

3.2.6

3 years ago

3.2.5

3 years ago

3.2.4

3 years ago

3.2.2

3 years ago

3.2.3

3 years ago

3.2.1

3 years ago

3.2.0

3 years ago

3.1.18

3 years ago

3.1.17

3 years ago

3.1.16

3 years ago

3.1.15

3 years ago

3.1.14

3 years ago

3.1.13

3 years ago

3.1.12

3 years ago

3.1.11

3 years ago

3.1.10

3 years ago

3.1.9

3 years ago

3.1.8

3 years ago

3.1.7

3 years ago

3.1.6

3 years ago

3.1.5

3 years ago

3.1.4

3 years ago

3.1.0

3 years ago

3.0.1

3 years ago

3.0.0

3 years ago

2.1.5

3 years ago

2.1.4

3 years ago

2.1.3

3 years ago

2.1.2

3 years ago

2.1.1

3 years ago

2.1.0

3 years ago

2.0.0

3 years ago

1.3.2

3 years ago

1.3.1

3 years ago

1.3.0

3 years ago

1.2.18

3 years ago

1.2.17

4 years ago

1.2.16

4 years ago

1.2.15

4 years ago

1.2.14

4 years ago

1.2.13

4 years ago

1.2.12

4 years ago

1.2.11

4 years ago

1.2.10

4 years ago

1.2.9

4 years ago

1.2.8

4 years ago

1.2.7

4 years ago

1.2.6

4 years ago

1.2.5

4 years ago

1.2.4

4 years ago

1.2.3

4 years ago

1.2.2

4 years ago

1.2.1

4 years ago

1.2.0

4 years ago

1.1.21

4 years ago

1.1.20

4 years ago

1.1.19

4 years ago

1.1.18

4 years ago

1.1.16

4 years ago

1.1.17

4 years ago

1.1.15

4 years ago

1.1.14

4 years ago

1.1.12

4 years ago

1.1.13

4 years ago

1.1.11

4 years ago

1.1.10

4 years ago

1.1.9

4 years ago

1.1.8

4 years ago

1.1.5

4 years ago

1.1.4

4 years ago

1.1.3

4 years ago

1.1.2

4 years ago

1.1.1

5 years ago

1.1.0

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago

0.2.2

5 years ago

0.2.1

5 years ago

0.2.0

5 years ago

0.1.21

5 years ago

0.1.20

5 years ago

0.1.19

5 years ago

0.1.18

5 years ago

0.1.17

5 years ago

0.1.16

5 years ago

0.1.15

5 years ago

0.1.14

5 years ago

0.1.13

5 years ago

0.1.12

5 years ago

0.1.11

5 years ago

0.1.10

5 years ago

0.1.9

5 years ago

0.1.8

5 years ago

0.1.7

5 years ago

0.1.6

5 years ago

0.1.5

5 years ago

0.1.4

5 years ago

0.1.3

5 years ago

0.1.2

5 years ago

0.1.1

5 years ago

0.1.0

5 years ago