Color Palette Generator
Build palettes from six harmony rules, lock the swatches you like, audit every color against WCAG contrast minimums, and export through a plugin registry — CSS variables, Tailwind, SCSS, JSON design tokens, or SVG. Settings persist, three UI themes ship built in, and nothing leaves your browser.
⚙️ Settings
Locked swatches survive every regenerate. Press space anywhere outside a field to roll a new palette.
🔌 Export plugins
Placeholders: {{hex}}, {{rgb}}, {{hsl}}, {{index}}, {{name}}, {{allHex}}. Registered plugins join the chip row above and persist across reloads.
🔍 Contrast audit (WCAG 2.2)
Ratio is computed against the swatch as background. AA needs 4.5:1 for body text, AAA needs 7:1 — the thresholds from WCAG 2.2 SC 1.4.3.
⭐ Saved palettes
Nothing saved yet — click “Save palette” to keep one. The last 12 live in this browser only.
How the Color Palette Generator works
Two layers: a harmony engine that turns one hue into a balanced ramp, and a plugin registry that turns the palette into whatever your build system wants. Everything below is the code actually running on this page.
Harmony math with per-swatch locks
Why learn this
Most palettes are assembled by eye, one color at a time, and the result usually collapses the moment you need a sixth shade. Harmony rules invert that workflow: pick a base hue, pick a relationship on the color wheel, and the rest is arithmetic. The arithmetic is not a matter of taste — hue offsets and lightness steps produce a set that is internally consistent by construction, which is why design systems ship ramps rather than hand-picked swatches.
What you built
A generator that converts your base color to HSL, applies a harmony offset per slot, then walks lightness up and down in equal steps so the ramp reads as one family. Six rules ship: analogous (clustered hues), complementary (opposing pair), triadic (three-way split), tetradic (four-way), monochrome (one hue, pure lightness ramp), and random. Saturation is clamped to a floor so no swatch turns muddy, and every value is clamped to 8–92% lightness to keep white and black text usable.
Key concepts
- HSL is the working space. Hue rotation is a single addition in HSL; in RGB it is a matrix multiply. Conversion happens at the edges — hex in, hex out.
- Locked slots are excluded from generation. The generator writes only to unlocked indices, so the colors you keep survive every roll. That single rule is what turns a randomizer into a design tool.
- Even offsets, uneven lightness. Hue offsets are distributed across the wheel; lightness uses a centered ramp so the middle swatch sits at your base lightness.
- Clamping is a safety rail. Without a lightness clamp, triadic palettes routinely emit near-white swatches where no text is legible.
- WCAG contrast is computed, not guessed. Relative luminance uses the sRGB linearization from WCAG 2.2: gamma-expand each channel, weight by 0.2126 / 0.7152 / 0.0722, then apply (L1 + 0.05) / (L2 + 0.05).
Alternative approaches
Perceptual spaces — CIELAB, OKLCH — produce more even ramps than HSL because HSL's lightness is not perceptually uniform. OKLCH is now well supported in CSS Color 4, but it needs a full color-science conversion chain in JavaScript to generate previews, and the payoff for a five-swatch ramp is small. HSL wins here because every intermediate value is trivially explainable in the tutorial, and because the output is plain hex that any older browser renders.
Browser compatibility
Generation uses only arithmetic on numbers — no canvas, no CSS color parsing, no dependency on color-mix() for the palette itself. The one modern CSS function in the UI is color-mix() on the active plugin chip, which degrades to a plain border in older browsers. The file download path uses Blob and URL.createObjectURL, both baseline since 2015.
Performance notes
A regenerate is eight HSL conversions plus eight contrast pairs — under 0.3 ms. Rendering dominates, so swatches are built once per roll as a single string and assigned to one container. There is no animation loop, no canvas, and no layout thrash.
Common pitfalls
- Forgetting the modulo.
hwraps at 360; a negative offset on a base hue of 10 produces −20, which is invalid and renders as black. - Rounding hex twice. Round each RGB channel once on the way out. Rounding HSL and then RGB drifts the swatch away from the value you displayed.
- Trusting HSL lightness for contrast. L=50% is not a contrast guarantee — a saturated yellow at L=50% carries far more luminance than a blue at L=50%.
- Regenerating locked swatches. The bug is subtle: locked colors look stable until the palette size changes and indices shift.
const OFFSETS = {
analogous: [0, 30, -30, 60, -60, 15, -15, 45],
complementary:[0, 180, 30, 210, -30, 150, 60, 240],
triadic: [0, 120, 240, 30, 150, 270, 60, 180],
tetradic: [0, 90, 180, 270, 45, 135, 225, 315],
monochrome: [0, 0, 0, 0, 0, 0, 0, 0]
};
function generate(opts, current) {
const base = hexToHsl(opts.baseHex);
const n = opts.size;
const offs = OFFSETS[opts.harmony] || OFFSETS.random;
const mid = (n - 1) / 2;
return Array.from({ length: n }, (_, i) => {
const locked = current[i] && current[i].locked;
if (locked) return current[i];
const hue = (base.h + offs[i] + jitter(opts.spread)) % 360;
return {
h: (hue + 360) % 360,
s: clamp(base.s + rand(-8, 8), opts.satFloor, 95),
l: clamp(base.l + (i - mid) * opts.lightStep, 8, 92),
locked: false
};
});
} function luminance(hex) {
const [r, g, b] = hexToRgb(hex).map((v) => {
const c = v / 255;
return c <= 0.03928
? c / 12.92
: Math.pow((c + 0.055) / 1.055, 2.4);
});
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
function contrast(a, b) {
const l1 = luminance(a), l2 = luminance(b);
const hi = Math.max(l1, l2), lo = Math.min(l1, l2);
return (hi + 0.05) / (lo + 0.05);
} WCAG 2.2 sets 4.5:1 for normal text (AA) and 7:1 for AAA; large text relaxes to 3:1 and 4.5:1. The badges on each swatch report both thresholds so you can see at a glance whether a ramp is usable for body copy.
Export through a plugin registry
Why learn this
Every exporter you will ever need — CSS variables, a Tailwind theme, SCSS vars, design tokens, an SVG sheet — is the same operation: take an array of colors, emit a string, name a file extension. Writing those as branches inside one function is how tools rot. A registry inverts the control: the core knows nothing about Tailwind, and a new format is one object added from anywhere, including at runtime from the UI.
What you built
A Plugins registry with a validation contract — every plugin must supply id, name, ext, and render(palette). Five ship built in: CSS custom properties, a Tailwind colors object, SCSS variables, a JSON design-token document, and an SVG swatch sheet. A sixth is registerable live from the settings panel: you type a template with placeholders, it compiles into a plugin, joins the chip row, and persists in localStorage. Custom plugins are marked with a ✦ so they are never confused with built-ins.
Key concepts
- One contract, many formats.
render(palette)returns a string. Nothing else about a plugin is known to the core, so formats are added without editing the app. - Templates instead of eval. The runtime plugin path uses placeholder substitution, not
new Function(). That keeps the feature CSP-safe and means a typo produces a literal string, not a crash. - Persistence with a schema version. Saved plugins and settings are stored under versioned keys; unknown fields are ignored on load so an older payload never breaks a newer build.
- Download, not just copy. Plugins declare their extension, so the same chip that renders CSS writes
palette.cssand the SVG plugin writespalette.svg.
Alternative approaches
The classic alternative is a switch statement over a format enum — fine for three formats, wrong at six, fatal once users want their own. A second alternative is loading exporters as modules, which requires network requests and a build step, both of which break the offline promise. Template substitution sits in the middle: expressive enough for real formats, small enough to audit in one screen.
Browser compatibility
The registry is a plain array with a validation gate. Storage uses localStorage inside a try/catch so private-mode browsers simply lose persistence instead of throwing. Clipboard writes prefer navigator.clipboard.writeText and fall back to a hidden textarea plus document.execCommand('copy').
Performance notes
Rendering one export is a single string build over at most eight colors; switching chips re-renders only the output textarea. Custom plugins are parsed once at registration and stored in the same array as built-ins, so the render path has no special cases.
Common pitfalls
- Duplicate ids. Registering the same id twice silently creates two chips; reject on collision and report it.
- Unsanitised names in downloads. A plugin named with a slash produces a broken download path. Slugify before
download(). - Reading storage without try/catch. Safari private mode throws on
setItem, and an unguarded write kills the rest of the init function. - Leaking the container. Rendering into one element and forgetting to reset it on chip switch stacks outputs.
const Plugins = {
list: [],
register(plugin) {
if (!plugin || typeof plugin.render !== 'function'
|| !plugin.id || !plugin.name || !plugin.ext) {
throw new Error('plugin needs id, name, ext, render');
}
if (this.list.some((p) => p.id === plugin.id)) {
throw new Error('duplicate plugin id: ' + plugin.id);
}
this.list.push(plugin);
return plugin;
},
render(id, palette) {
const p = this.list.find((x) => x.id === id)
|| this.list[0];
return p.render(palette);
}
};
Plugins.register({
id: 'css', name: 'CSS variables', ext: 'css',
render: (pal) => ':root {\n' + pal.map((c, i) =>
' --color-' + (i + 1) + ': ' + c.hex + ';'
).join('\n') + '\n}\n'
}); function compileTemplate(name, ext, template) {
return {
id: 'custom-' + name.toLowerCase()
.replace(/[^a-z0-9]+/g, '-'),
name, ext, custom: true,
render: (pal) => pal.map((c, i) =>
template
.replace(/{{hex}}/g, c.hex)
.replace(/{{rgb}}/g, c.rgb)
.replace(/{{hsl}}/g, c.hsl)
.replace(/{{index}}/g, String(i + 1))
.replace(/{{name}}/g, 'color-' + (i + 1))
.replace(/{{allHex}}/g,
pal.map((x) => x.hex).join(', '))
).join('\n')
};
} The moment you write the third exporter as an if branch, stop and build the registry. The branch count never shrinks; the registry count does not grow at all.
Lessons learned
What the difficulty ramp actually forced, and what I would keep if the tool had to shrink back to a weekend build.
A random palette generator is a toy for about ninety seconds. The lock button is what makes it a design tool: you keep the two colors that work and reroll the rest. Before locks, every regenerate threw away your progress; after them, generation becomes iterative search. If a future revision adds anything, it should deepen this loop — lock by role, not just by index.
Seven controls — harmony, size, spread, saturation floor, lightness step, base color, theme — is already more state than a hand-wired UI can hold. The fix was one state object, one readSettings() from the DOM, one applySettings() to the DOM, and a single versioned storage key. Every input listener calls the same two functions. No control owns behavior.
The registry rejects a plugin missing id, name, ext, or a render function, and rejects duplicate ids. That is ten lines and it converts «read the docs» into «the app tells you». Web components and most plugin hosts use the same shape: validate at the boundary, assume nothing after it.
Every generated palette is one bad ramp away from an accessibility failure, so the audit is not a separate mode — it is a badge on each swatch. Computing luminance is fifteen lines and it catches the exact case HSL hides: a mid-lightness yellow that looks fine and fails AA on white. See CSS Color 4 for the perceptual spaces that would make ramps even.
Two layers, one contract each: harmony math writes colors, and the plugin registry turns them into files. Every feature added at level 10 — settings, themes, runtime plugins — builds on those two seams instead of cutting across them, which is why the whole thing still fits in one file with no dependencies.