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,rgbToHexandrandomColorare 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
new Color(
r: string | number | Array<string | number>,
g?: string | number,
b?: string | number,
a?: string | number,
)Parameters
| Parameter | Description | Type | Default |
|---|---|---|---|
r | Red channel. A hex string (#f00 / #ff0000, with or without #), an [r, g, b, a?] array, or a number | string | number | Array<string | number> | Required |
g | Green channel (ignored when r is a string or array) | string | number | 0 |
b | Blue channel (ignored when r is a string or array) | string | number | 0 |
a | Alpha channel (0–1) | string | number | 1.0 |
Properties
| Property | Description | Type |
|---|---|---|
r | Red channel (0–255) | string | number |
g | Green channel (0–255) | string | number |
b | Blue channel (0–255) | string | number |
a | Alpha channel (0–1) | string | number |
h | Hue (0–360), mirrors hsl.h | string | number |
s | Saturation (0–100), mirrors hsl.s | string | number |
l | Lightness (0–100), mirrors hsl.l | string | number |
rgb | RGB value object | Rgb |
rgba | RGBA value object | Rgba |
hex | Hexadecimal string (e.g. #ff0000) | string |
hsl | HSL value object | Hsl |
hsla | HSLA value object | Hsla |
Methods
| Method | Description | Return |
|---|---|---|
setHue(newHue) | Set hue and recompute RGB/hex from HSL | void |
setSat(newSat) | Set saturation and recompute RGB/hex from HSL | void |
setLum(newLum) | Set lightness and recompute RGB/hex from HSL | void |
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
new Rgb(col: Array<string | number>) // [r, g, b]Properties & Methods
| Member | Description | Type |
|---|---|---|
r | Red channel | string | number |
g | Green channel | string | number |
b | Blue channel | string | number |
toString() | Returns rgb(r,g,b) | string |
Rgba
Extends Rgb with an alpha channel. toString() returns a CSS rgba(...) string.
Constructor
new Rgba(col: Array<string | number>) // [r, g, b, a]Properties & Methods
| Member | Description | Type |
|---|---|---|
r g b | Inherited from Rgb | string | number |
a | Alpha channel | string | 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
new Hsl(col: Array<string | number>) // [h, s, l]Properties & Methods
| Member | Description | Type |
|---|---|---|
h | Hue (0–360) | string | number |
s | Saturation (0–100) | string | number |
l | Lightness (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
new Hsla(col: Array<string | number>) // [h, s, l, a]Properties & Methods
| Member | Description | Type |
|---|---|---|
h s l | Inherited from Hsl | string | number |
a | Alpha channel | string | 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
new ColorScheme(colorVal: (string | number)[], angleArray: number[])| Parameter | Description | Type |
|---|---|---|
colorVal | Base color, or (when angleArray is undefined) an array of colors to build the palette from | (string | number)[] |
angleArray | Hue offsets (degrees) applied to the base color to derive additional palette entries | number[] |
Properties & Methods
| Member | Description | Return |
|---|---|---|
palette | The generated colors | Color[] |
createFromColors(colorVal) | Build the palette from an array of colors | Color[] |
createFromAngles(colorVal, angleArray) | Build the palette from a base color plus hue offsets | Color[] |
Static factory methods
Each takes a base color value and returns a ColorScheme with a preset hue-angle set.
| Method | Hue angles | Scheme |
|---|---|---|
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])).
| Function | Description | Signature |
|---|---|---|
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,rgbToHexandhexToRgbare 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.
| Function | Description | Signature |
|---|---|---|
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.
| Function | Description | Signature |
|---|---|---|
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 a–d 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 |
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.5WARNING
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, '')).
| Constant | Matches |
|---|---|
HEX_COLOR_REGEX | #rgb / #rrggbb, # required, case-insensitive |
RGB_REGEX | rgb(r,g,b) |
RGBA_REGEX | rgba(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.
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
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
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
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
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
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
- Eager computation: A
Colorcomputes all representations in its constructor, sohex,rgb,rgba,hslandhslaare always in sync at construction time. - HSL setters recompute RGB:
setHue/setSat/setLumupdate HSL and then re-derive RGB and hex viaupdateFromHsl.setAlphaonly affectsrgbaandhsla. - Array-or-channels inputs: Several conversion functions (
rgbToHex,rgbToHsl,hslToRgb) accept either three channel arguments or a single array as the first argument. - HSV vs HSB:
hsvToRgbis an alias ofhsbToRgb, andhsvToHslan alias of the HSB→HSL conversion — HSV and HSB refer to the same model here. - 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.