Skip to content

Color

A class-based color system with conversion helpers for working with RGB, RGBA, HSL, HSLA, HSB/HSV and hexadecimal colors. It provides a rich Color class, immutable value classes (Rgb, Rgba, Hsl, Hsla), a ColorScheme palette generator, a set of standalone conversion functions, and the FMT terminal ANSI style map.

The simpler helpers hexToRgb, rgbToHex and randomColor are documented on their own pages: hexToRgb, rgbToHex, randomColor. They are re-exported from the same module.

API

Color

The main color class. It accepts a hex string, an [r, g, b, a] array, or separate channel numbers, and eagerly computes every representation (rgb, rgba, hex, hsl, hsla) plus flat channel accessors.

Constructor

ts
new Color(
  r: string | number | Array<string | number>,
  g?: string | number,
  b?: string | number,
  a?: string | number,
)

Parameters

ParameterDescriptionTypeDefault
rRed channel. A hex string (#f00 / #ff0000, with or without #), an [r, g, b, a?] array, or a numberstring | number | Array<string | number>Required
gGreen channel (ignored when r is a string or array)string | number0
bBlue channel (ignored when r is a string or array)string | number0
aAlpha channel (0–1)string | number1.0

Properties

PropertyDescriptionType
rRed channel (0–255)string | number
gGreen channel (0–255)string | number
bBlue channel (0–255)string | number
aAlpha channel (0–1)string | number
hHue (0–360), mirrors hsl.hstring | number
sSaturation (0–100), mirrors hsl.sstring | number
lLightness (0–100), mirrors hsl.lstring | number
rgbRGB value objectRgb
rgbaRGBA value objectRgba
hexHexadecimal string (e.g. #ff0000)string
hslHSL value objectHsl
hslaHSLA value objectHsla

Methods

MethodDescriptionReturn
setHue(newHue)Set hue and recompute RGB/hex from HSLvoid
setSat(newSat)Set saturation and recompute RGB/hex from HSLvoid
setLum(newLum)Set lightness and recompute RGB/hex from HSLvoid
setAlpha(newAlpha)Set alpha on both rgba and hsla (does not touch RGB/hex)void
updateFromHsl()Recompute rgb, channels and hex from the current h/s/l (called by the setters above)void

Rgb

An RGB value object built from an array. toString() returns a CSS rgb(...) string.

Constructor

ts
new Rgb(col: Array<string | number>) // [r, g, b]

Properties & Methods

MemberDescriptionType
rRed channelstring | number
gGreen channelstring | number
bBlue channelstring | number
toString()Returns rgb(r,g,b)string

Rgba

Extends Rgb with an alpha channel. toString() returns a CSS rgba(...) string.

Constructor

ts
new Rgba(col: Array<string | number>) // [r, g, b, a]

Properties & Methods

MemberDescriptionType
r g bInherited from Rgbstring | number
aAlpha channelstring | number
toString()Returns rgba(r,g,b,a)string

Hsl

An HSL value object built from an array. toString() returns a CSS hsl(...) string.

Constructor

ts
new Hsl(col: Array<string | number>) // [h, s, l]

Properties & Methods

MemberDescriptionType
hHue (0–360)string | number
sSaturation (0–100)string | number
lLightness (0–100)string | number
toString()Returns hsl(h,s%,l%)string

Hsla

Extends Hsl with an alpha channel. toString() returns a CSS hsla(...) string.

Constructor

ts
new Hsla(col: Array<string | number>) // [h, s, l, a]

Properties & Methods

MemberDescriptionType
h s lInherited from Hslstring | number
aAlpha channelstring | number
toString()Returns hsla(h,s%,l%,a)string

ColorScheme

Generates a palette of related Color objects — either directly from a list of colors, or from a base color rotated by an array of hue angles. Static factory methods cover common color-harmony schemes.

Constructor

ts
new ColorScheme(colorVal: (string | number)[], angleArray: number[])
ParameterDescriptionType
colorValBase color, or (when angleArray is undefined) an array of colors to build the palette from(string | number)[]
angleArrayHue offsets (degrees) applied to the base color to derive additional palette entriesnumber[]

Properties & Methods

MemberDescriptionReturn
paletteThe generated colorsColor[]
createFromColors(colorVal)Build the palette from an array of colorsColor[]
createFromAngles(colorVal, angleArray)Build the palette from a base color plus hue offsetsColor[]

Static factory methods

Each takes a base color value and returns a ColorScheme with a preset hue-angle set.

MethodHue anglesScheme
ColorScheme.Compl(colorVal)[180]Complementary
ColorScheme.Triad(colorVal)[120, 240]Triadic
ColorScheme.Tetrad(colorVal)[60, 180, 240]Tetradic
ColorScheme.Analog(colorVal)[-45, 45]Analogous
ColorScheme.Split(colorVal)[150, 210]Split-complementary
ColorScheme.Accent(colorVal)[-45, 45, 180]Accented analogous

Conversion functions

Standalone functions used internally by Color; each is exported for direct use. Where a function accepts three channel arguments, the first may also be a single array (e.g. rgbToHsl([r, g, b])).

FunctionDescriptionSignature
componentToHex(c)Convert one 0–255 channel to a two-digit hex string(c: string | number) => string
hue2rgb(p, q, t)HSL→RGB hue helper (used by hslToRgb)(p: number, q: number, t: number) => number
hslToRgb(h, s, l)HSL → [r, g, b] (0–255). Accepts [h, s, l] as the first arg(h, s, l) => number[]
rgbToHsl(r, g, b)RGB → [h, s, l]. Accepts [r, g, b] as the first arg(r, g, b) => number[]
rgbToHsb(r, g, b)RGB → [h, s, b] (HSB/HSV)(r: number, g: number, b: number) => number[]
hsbToRgb(h, s, v)HSB/HSV → [r, g, b] (0–255)(h: number, s: number, v: number) => number[]
hsvToRgb(h, s, v)Alias of hsbToRgb(h: number, s: number, v: number) => number[]
hsvToHsl(h, s, b)HSB/HSV → [h, s, l] (via rgbToHsl(hsbToRgb(...)))(h, s, b) => number[]
rgbToHsv(r, g, b)Alias of rgbToHsb(r: number, g: number, b: number) => number[]
hexToHsb(hex)#rrggbb / #rgb[h, s, b], or null on malformed input(hex: string) => number[] | null
hexToHsv(hex)Alias of hexToHsb(hex: string) => number[] | null
hsbToHsl(h, s, b)HSB/HSV → [h, s, l](h, s, b) => number[]
hslToHsb(h, s, l)HSL → [h, s, b](h, s, l) => number[]
hslToHsv(h, s, l)Alias of hslToHsb(h, s, l) => number[]

componentToHex, rgbToHex and hexToRgb are the low-level building blocks; see rgbToHex and hexToRgb.

Alpha helpers

Alpha is expressed as 0 – 100, matching the percentage scale the rest of this module uses for saturation and lightness — not the 0 – 1 that CSS rgba() takes.

FunctionDescriptionSignature
hexToAlpha(aa)A two-digit hex alpha channel (ff / 80 / 00) → 0 – 100(aa: string) => number
rgbaString(r,g,b,a)Build a CSS rgba() string; a is divided by 100(r, g, b, a) => string
rgbaToRgb(r,g,b,a)Composite a translucent colour onto white → opaque [r, g, b](r, g, b, a) => number[]
rgbaToHex(r,g,b,a)The same composite, returned as a 6-digit hex string(r, g, b, a) => string

WARNING

rgbaToRgb / rgbaToHex hard-code white as the backdrop. They exist for places that cannot accept an alpha channel (writing back a 6-digit hex, say). Under a dark theme the result will read too light — blend against your own backdrop instead.

Blend & shader-math helpers

The colour-grade and blend math behind ranuts/visual's post-processing filters (ColorAdjustFilter and friends), exported here for CPU-side reuse — computing a thumbnail preview, say, without spinning up a GPU pipeline. Unlike the rest of this module, channels here are 0–1, not 0–255 or 0–100 — the convention shaders use.

FunctionDescriptionSignature
luma(r, g, b)Perceived brightness (Rec. 601 weights). Keeps whatever scale the inputs are in — 0–1 or 0–255(r, g, b) => number
blendScreen(base, blend)Screen blend: 1 - (1-base)(1-blend) per channel(base: RGB, blend: RGB) => RGB
blendMultiply(base, blend)Multiply blend: base * blend per channel(base: RGB, blend: RGB) => RGB
blendOverlay(base, blend)Overlay: multiply in shadows, screen in highlights(base: RGB, blend: RGB) => RGB
brightnessContrast(color, b, c)(channel - 0.5) * contrast + 0.5 + brightness per channel(color: RGB, brightness, contrast) => RGB
saturation(color, amount)Mix toward luminance. 0 = greyscale, 1 = unchanged, >1 = more saturated(color: RGB, amount: number) => RGB
vibrance(color, amount)Like saturation, but saturates muted channels more than already-saturated ones. >0 boosts, <0 mutes(color: RGB, amount: number) => RGB
cosinePalette(t, a, b, c, d)Inigo Quilez cosine gradient: a + b·cos(2π(c·t + d)), each of ad an RGB triple, t the position 0–1(t, a: RGB, b: RGB, c: RGB, d: RGB) => RGB
srgbToLinear(c) / linearToSrgb(c)Convert one channel between sRGB (what you read from a hex color) and linear light (what shader math wants)(c: number) => number
ts
import { blendScreen, brightnessContrast, cosinePalette, srgbToLinear, linearToSrgb } from 'ranuts/utils';

// Screen-blend two 0-1 colors
const screened = blendScreen([0.8, 0.2, 0.1], [0.1, 0.5, 0.9]);

// Push contrast up and brightness down slightly
const graded = brightnessContrast([0.6, 0.6, 0.6], -0.05, 1.2);

// Sample a procedural gradient palette at t=0.35
const swatch = cosinePalette(0.35, [0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [1, 1, 1], [0, 0.33, 0.67]);

// Gamma-correct math (blending, lighting) should happen in linear space
const linear = srgbToLinear(0.5);
const backToSrgb = linearToSrgb(linear); // ≈ 0.5

WARNING

Blend and grade math operates on linear-light values for physically-correct results — an 8-bit hex color is sRGB-encoded, so run it through srgbToLinear first if the blend needs to look right rather than merely compile.

Format patterns

Regular expressions for validating colour strings. RGB_REGEX and RGBA_REGEX do not tolerate spaces — strip them first (value.replace(/\s+/g, '')).

ConstantMatches
HEX_COLOR_REGEX#rgb / #rrggbb, # required, case-insensitive
RGB_REGEXrgb(r,g,b)
RGBA_REGEXrgba(r,g,b,a)

FMT

A record of ANSI terminal escape-code pairs for text styling and coloring. Each entry is a [open, close] tuple you wrap around a string to style terminal output.

ts
const FMT: Record<string, Array<string>>;

Available keys: bold, dim, reset, italic, underline, inverse, hidden, strikethrough, black, red, green, yellow, blue, magenta, cyan, white, gray, and the background variants bgBlack, bgRed, bgGreen, bgYellow, bgBlue, bgMagenta, bgCyan, bgWhite.

Example

Creating a Color

js
import { Color } from 'ranuts';

// From a hex string (short or long form, # optional)
const red = new Color('#ff0000');
console.log(red.hex); // '#ff0000'
console.log(red.rgb.toString()); // 'rgb(255,0,0)'
console.log(red.hsl.toString()); // 'hsl(0,100%,50%)'

// From channels
const green = new Color(0, 255, 0);
console.log(green.hex); // '#00ff00'

// From an array (with alpha)
const blue = new Color([0, 0, 255, 0.5]);
console.log(blue.rgba.toString()); // 'rgba(0,0,255,0.5)'

Mutating a Color via HSL

js
import { Color } from 'ranuts';

const color = new Color('#ff0000');

color.setHue(120); // rotate hue to green
console.log(color.rgb.toString()); // 'rgb(0,255,0)'

color.setLum(25); // darker
color.setSat(50); // desaturate
color.setAlpha(0.4);
console.log(color.rgba.toString()); // 'rgba(...,0.4)'

Building a palette with ColorScheme

js
import { ColorScheme } from 'ranuts';

// Complementary pair from a base color
const compl = ColorScheme.Compl('#3498db');
console.log(compl.palette.map((c) => c.hex));

// Triadic scheme (base + two colors 120° apart)
const triad = ColorScheme.Triad('#3498db');
console.log(triad.palette.length); // 3

// Directly from a list of colors
const custom = new ColorScheme(['#ff0000', '#00ff00', '#0000ff']);
console.log(custom.palette.map((c) => c.hsl.toString()));

Using the conversion functions

js
import { rgbToHsl, hslToRgb, rgbToHsb, hsbToRgb, componentToHex } from 'ranuts';

console.log(rgbToHsl(255, 0, 0)); // [0, 100, 50]
console.log(hslToRgb(0, 100, 50)); // [255, 0, 0]
console.log(rgbToHsb(255, 0, 0)); // [0, 100, 100]
console.log(hsbToRgb(0, 100, 100)); // [255, 0, 0]
console.log(componentToHex(255)); // 'ff'

// Array input is also accepted where documented
console.log(rgbToHsl([0, 128, 255])); // [h, s, l]

Styling terminal output with FMT

js
import { FMT } from 'ranuts';

const [open, close] = FMT.green;
console.log(`${open}success${close}`); // green "success" in a terminal

const bold = FMT.bold;
console.log(`${bold[0]}important${bold[1]}`);

Notes

  1. Eager computation: A Color computes all representations in its constructor, so hex, rgb, rgba, hsl and hsla are always in sync at construction time.
  2. HSL setters recompute RGB: setHue / setSat / setLum update HSL and then re-derive RGB and hex via updateFromHsl. setAlpha only affects rgba and hsla.
  3. Array-or-channels inputs: Several conversion functions (rgbToHex, rgbToHsl, hslToRgb) accept either three channel arguments or a single array as the first argument.
  4. HSV vs HSB: hsvToRgb is an alias of hsbToRgb, and hsvToHsl an alias of the HSB→HSL conversion — HSV and HSB refer to the same model here.
  5. FMT is terminal-only: The ANSI escape sequences render as styling only in a terminal that supports them; in a browser console they appear as raw control characters.

Released under the MIT License.