Skip to main content

Color - Play with Colors Convert, blend, manipulate and do more

Color

The Color class provides a robust way to work with colors in various formats (i.e. Hex, Hex8, RGB, HSL, RGBA, HSLA) and includes methods for color manipulation, blending, and accessibility checks.


Available Methods


Import

import { Color } from 'nhb-toolbox';
// or
import { Color } from 'nhb-toolbox/color';

Constructor & Signatures

Creates a new Color instance from various input formats.

// Generates a random color
constructor();
// Using hex, rgb or hsl colors with or without alpha channel
constructor(color: ColorType);
// Using a CSS named color
constructor(color: CSSColor);
// Using specific color format (ColorType) or CSS named color
constructor(color?: ColorType | CSSColor); // Use this signature in type ambiguous situation(s).

Type Definitions

Hex

type Hex = `#${string}`; // Format: #3C6945

Hex6

type Hex6 = Branded<Hex, 'Hex6'>; // Format: #3C6945

Hex8

type Hex8 = Branded<Hex, 'Hex8'>; // Format: #3C6945FF (with alpha channel)

RGB

type RGB = `rgb(${number}, ${number}, ${number})` | `rgb(${number},${number},${number})`; // Format: rgb(R, G, B)

RGBA

type RGBA = `rgba(${number}, ${number}, ${number}, ${number})` | `rgba(${number},${number},${number},${number})`; // With alpha channel

HSL

type HSL = `hsl(${number}, ${number}%, ${number}%)` | `hsl(${number},${number}%,${number}%)`; // Format: hsl(H, S%, L%)

HSLA

type HSLA = `hsla(${number}, ${number}%, ${number}%, ${number})` | `hsla(${number},${number}%,${number}%,${number})`; // With alpha channel

ColorType

// Union of Alpha & Solid `Hex`, `RGB` and `HSL`
type ColorType = Hex | Hex6 | RGB | HSL | Hex8 | RGBA | HSLA;

CSSColor

type CSSColor = "black" | "silver" | "gray" | "white" | "maroon" | "red" | "purple" | "fuchsia" | "green" | "lime" | "olive" | "yellow" | "navy" | "blue" | "teal" | "aqua" | "aliceblue" | "antiquewhite" | "aquamarine" | "azure" | "beige" | "bisque" | "blanchedalmond" | "blueviolet" | "brown" | "burlywood" | "cadetblue" | "chartreuse" | "chocolate" | "coral" | "cornflowerblue" | "cornsilk" | "crimson" | "cyan" | "darkblue" | "darkcyan" | "darkgoldenrod" | "darkgray" | "darkgreen" | "darkgrey" | "darkkhaki" | "darkmagenta" | "darkolivegreen" | "darkorange" | ... 112 more ... | "error"; // All valid (150+) CSS color names

Percent

type Percent = 0 | 1 | 2 | ... | 100; // 0-100

Alias

Color can also be imported using Colour alias:

import { Colour } from 'nhb-toolbox';
// or
import { Colour } from 'nhb-toolbox/color';

See Also