Skip to main content

Colors

Hex-string colour maths — conversion to and from RGB, lightening and darkening by a percentage, a contrast-aware text colour, and random colours. Hex is the only input format because it is what CSS, design tokens and config files already carry; there is no colour-space interpolation and no perceptual (OKLCH/LAB) maths. randomColor draws from Math.random, so treat its output as decoration, never as an identifier.

Example

import { darken, isValidHex, lighten, matchingTextColor } from '@rtorcato/js-common/colors'

// One brand hex from a config file, a whole button state set out of it.
const brand = '#2f6feb'

isValidHex(brand) // true
lighten(brand, 0.2) // '#588bef' — 20% of the way to white (hover)
darken(brand, 0.2) // '#2558bc' — 20% of the way to black (active)
matchingTextColor(brand) // '#fff' — whichever of black/white reads on it

Import

import { darken, hexToRgb, isValidHex } from '@rtorcato/js-common/colors'

Exports

NameSummary
darkenDarkens a hex color by a given percentage.
hexToRgbConverts a hex color string to an RGB object.
isValidHexChecks whether a string is a valid 3- or 6-digit hex colour.
lightenLightens a hex color by a given percentage.
matchingTextColorPicks the readable text colour (#000 or #fff) for a hex background.
randomColorGenerates a random hex color string.
rgbToHexConverts RGB values to a hex color string.

See also

  • random — random ints, floats, strings and array picks
  • geometry — 2D distance, angle, midpoint, hit-testing
  • numbers — sum, average, clamp, roundTo