Skip to content

Cookbook

Generate an accessible button palette

ts
import { colorShades, bestTextColor, wcagLevel } from 'color-value-tools'

function buttonPalette(base: string) {
  return colorShades(base, 9).map((shade) => ({
    bg: shade,
    text: bestTextColor(shade),
    wcag: wcagLevel(bestTextColor(shade), shade),
  }))
}

buttonPalette('#3498db')
// [{ bg: '#ffffff', text: '#000000', wcag: 'AAA' }, ...]

Theme-aware color adaptation

ts
import { isDark, lighten, darken } from 'color-value-tools'

function adaptToTheme(color: string, isDarkTheme: boolean): string {
  return isDarkTheme ? lighten(color, 20) : darken(color, 10)
}

Mix two brand colors at a perceptual midpoint

ts
import { midpointColor } from 'color-value-tools'

const mid = midpointColor('#e74c3c', '#3498db') // Oklab midpoint
const midLch = midpointColor('#e74c3c', '#3498db', { space: 'oklch' })

Build a triadic scheme and check contrast

ts
import { triadic, contrastRatio } from 'color-value-tools'

const [base, second, third] = triadic('#6c3483')
console.log(contrastRatio(base, '#ffffff')) // e.g. 8.4
console.log(contrastRatio(second, '#ffffff'))

Convert any color string to all formats at once

ts
import { normalizeColor, rgbToOklch, rgbToCmyk, toColorP3String } from 'color-value-tools'

const n = normalizeColor('hsl(204, 70%, 53%)')
const oklch = rgbToOklch({ r: n.r!, g: n.g!, b: n.b! })
const cmyk = rgbToCmyk({ r: n.r!, g: n.g!, b: n.b! })
const p3 = toColorP3String(n.hex!)
console.log(n.hex, oklch, cmyk, p3)

Find the nearest CSS named color

ts
import { toNearestNamedColor } from 'color-value-tools'

toNearestNamedColor('#1a8ccc') // 'steelblue'
toNearestNamedColor('#e74c3c') // 'tomato'

Random palette within a hue range

ts
import { randomColor, colorShades } from 'color-value-tools'

const accent = randomColor({ hRange: [200, 260], sRange: [60, 80], lRange: [40, 60] })
const palette = colorShades(accent, 5)

Simulate color blindness for a palette

ts
import { triadic, simulateColorBlindness } from 'color-value-tools'

const palette = triadic('#e74c3c')
const deuteranopia = palette.map((c) => simulateColorBlindness(c, 'deuteranopia'))
// Compare palette vs deuteranopia to verify distinguishability

Lazy gradient — process 10 000 colors one at a time

ts
import { generateGradientColors } from 'color-value-tools'

for (const color of generateGradientColors('#1a1a2e', '#f5a623', 10_000, { mode: 'oklch' })) {
  ctx.fillStyle = color
  ctx.fillRect(x++, 0, 1, height)
}