# color2k
> Small, zero-dependency JavaScript color manipulation and WCAG contrast library with TypeScript types
Website: https://color2k.com/ | Source: https://github.com/ricokahler/color2k | npm: https://www.npmjs.com/package/color2k
## Rules
- Install with `npm i color2k`. Use named imports: `import { darken, toHex } from 'color2k'`. There is no default export and no chaining.
- Colors go in as CSS strings, and functions that produce a color return a CSS string. Inputs can be hex (3, 4, 6 or 8 digits), comma-separated `rgb()`, `rgba()`, `hsl()` or `hsla()`, a named color, or `transparent`.
- Amounts are decimals from 0 to 1 and are absolute. `darken(color, 0.1)` lowers lightness by 10 percentage points. It is not a 10% relative change.
- `darken`, `lighten`, `saturate`, `desaturate` and `adjustHue` return `hsla()` strings. `transparentize`, `opacify` and `mix` return `rgba()` strings, and so does the function `getScale` gives you. Wrap a result in `toHex` when you need hex.
- `mix(color1, color2, weight)`: weight 0 gives `color1` and weight 1 gives `color2`, always as an `rgba()` string.
- `getScale('red', 'yellow', 'green')` takes colors as separate arguments, not an array, and returns a function, not a color: call it with a number from 0 to 1.
- `readableColor(background)` returns `'#000'` or `'#fff'`. `hasBadContrast(color, standard = 'aa', background = '#fff')` returns `true` when contrast is too low.
- A string color2k can't parse throws a `ColorError`. Space-separated `rgb(0 0 0 / 50%)`, percentage alpha, `oklch()`, `lab()` and `color()` are not supported.
- Parsing is loose and is not validation: `rgb(999, 0, 0)` is accepted as written and not clamped, and about 3% of made-up color names parse as some color. Validate user input yourself before passing it in (`CSS.supports` is not equivalent: it accepts forms color2k rejects).
- `getContrast`, `hasBadContrast` and `readableColor` ignore alpha. Flatten a see-through color onto its background before measuring.
- `adjustHue` does not wrap hues below 0. If the color's hue plus the degrees is negative (`adjustHue('red', -120)`), the result is `hsla(-120, ...)`, which color2k throws on if you pass it back in (a known bug). Add 360 to a negative angle to avoid it.
- sRGB only. There are no CMYK, LAB or wide-gamut conversions.
## Quickstart
```
npm i color2k
```
```js
import { darken, mix, readableColor, toHex } from 'color2k';
darken('rebeccapurple', 0.1); // 'hsla(270, 50%, 30%, 1)'
mix('gold', 'tomato', 0.5); // 'rgba(255, 157, 36, 1)'
readableColor('gold'); // '#000'
toHex('rgb(102, 51, 153)'); // '#663399'
```
Colors go in as CSS strings. Amounts are decimals from 0 to 1.
color2k ships ES modules, CommonJS and a UMD build, so it works without a bundler too.
In Node.js with `require`:
```js
const { darken } = require('color2k');
darken('white', 0.1); // 'hsla(0, 0%, 90%, 1)'
```
In the browser as a module:
```html
```
Or as a global named `color2k`:
```html
```
### Browser and Node support
The CommonJS build runs on Node 6, and CI runs it there on every change. The ES module and UMD builds are written in ES2015 syntax, so they load in any browser that understands ES2015 without a compile step. TypeScript types ship in the package.
## API
### adjustHue(color, degrees)
```ts
function adjustHue(color: string, degrees: number): string
```
Rotates a color's hue by the given number of degrees and returns the result
as an `hsla` string.
A hue past 360 wraps around the color wheel. A hue below 0 does not: when
the color's own hue plus `degrees` is negative, the result has a negative
hue. `adjustHue('red', -120)` returns `hsla(-120, 100%, 50%, 1)`, which
browsers understand but color2k cannot parse again. `adjustHue('blue', -120)`
is fine, because blue's hue is 240.
```js
adjustHue('red', 180); // 'hsla(180, 100%, 50%, 1)'
```
Returns `string`: The adjusted color as an `hsla` string.
### ColorError
```ts
class ColorError extends Error
```
Error thrown when color2k cannot parse an input color.
```js
new ColorError('nope').message; // 'Failed to parse color: "nope"'
```
### complement(color)
```ts
function complement(color: string): string
```
Rotates a color's hue by 180 degrees and returns the result as an `hsla`
string, like Sass's `complement`.
Like `adjustHue`, the result is rounded to whole degrees and percents, so
each channel can be up to 5 away from Sass's exact result. Grays have no hue
and keep their color, but their channels can move by 1 from that rounding.
```js
complement('red'); // 'hsla(180, 100%, 50%, 1)'
```
Returns `string`: The complementary color as an `hsla` string.
### darken(color, amount)
```ts
function darken(color: string, amount: number): string
```
Darkens a color by subtracting from the lightness channel in HSL space.
```js
darken('white', 0.1); // 'hsla(0, 0%, 90%, 1)'
```
Returns `string`: The darkened color as an `hsla` string.
### desaturate(color, amount)
```ts
function desaturate(color: string, amount: number): string
```
Desaturates a color by subtracting from the saturation channel in HSL space.
```js
desaturate('red', 0.5); // 'hsla(0, 50%, 50%, 1)'
```
Returns `string`: The desaturated color as an `hsla` string.
### getContrast(color1, color2)
```ts
function getContrast(color1: string, color2: string): number
```
Returns the contrast ratio between two colors based on the WCAG contrast
ratio formula.
The ratio is between 1 and 21 for opaque, in-range colors. Alpha is ignored,
and out-of-range channels such as `rgb(999, 0, 0)` are not clamped, so they
give ratios that mean nothing.
```js
getContrast('#444', '#fff'); // 9.739769120526205
```
Returns `number`: The contrast ratio between the two colors.
### getLuminance(color)
```ts
function getLuminance(color: string): number
```
Returns the relative luminance of a color using the WCAG formula.
```js
getLuminance('papayawhip'); // 0.877971001998354
```
Returns `number`: A number between 0 for darkest black and 1 for lightest white.
### getScale(...colors)
```ts
function getScale(...colors: string[]): (n: number) => string
```
Returns a scale function that interpolates through a list of colors.
Pass at least two colors. With fewer there is nothing to interpolate
between, and the scale has no colors to return.
The returned function accepts a decimal between 0 and 1 and returns the color
at that percentage in the scale.
```js
const scale = getScale('red', 'yellow', 'green');
console.log(scale(0)); // rgba(255, 0, 0, 1)
console.log(scale(0.5)); // rgba(255, 255, 0, 1)
console.log(scale(1)); // rgba(0, 128, 0, 1)
```
With a single color, the scale always returns that color.
If you'd like to limit the domain and range like chroma-js, we recommend
wrapping scale again.
```js
const _scale = getScale('red', 'yellow', 'green');
const scale = x => _scale(x / 100);
console.log(scale(0)); // rgba(255, 0, 0, 1)
console.log(scale(50)); // rgba(255, 255, 0, 1)
console.log(scale(100)); // rgba(0, 128, 0, 1)
```
Returns `(n: number) => string`: A function that maps a decimal percentage to an `rgba` color.
### guard(low, high, value)
```ts
function guard(low: number, high: number, value: number): number
```
Clamps a number between a lower and upper bound.
```js
guard(0, 1, 2); // 1
```
Returns `number`: The clamped number.
### hasBadContrast(color, standard, background)
```ts
function hasBadContrast(color: string, standard: 'decorative' | 'readable' | 'aa' | 'aaa' = 'aa', background: string = '#fff'): boolean
```
Returns whether a color fails a contrast threshold against a background.
The standards and the minimum contrast ratio each one needs are `decorative`
(1.5), `readable` (3), `aa` (4.5), and `aaa` (7). By default the color is
checked against `aa` on a white (`#fff`) background.
```js
hasBadContrast('red', 'aa'); // true
```
Returns `boolean`: `true` when the contrast ratio is below the selected standard.
### hsla(hue, saturation, lightness, alpha)
```ts
function hsla(hue: number, saturation: number, lightness: number, alpha: number): string
```
Builds an `hsla` color string from hue, saturation, lightness, and alpha
channel values.
```js
hsla(0, 1, 0.5, 1); // 'hsla(0, 100%, 50%, 1)'
```
Returns `string`: An `hsla` color string.
### invert(color, weight)
```ts
function invert(color: string, weight: number = 1): string
```
Inverts a color's red, green, and blue channels, keeping its alpha, and
returns the result as an `rgba` string. This matches Sass's `invert`.
`weight` controls how far to go toward the inverse: `1` (the default) fully
inverts the color, `0` returns it unchanged, and `0.5` always gives gray.
Weights outside 0 to 1 are clamped to that range. A weight that is not a
finite number (`NaN` or `Infinity`) throws a `RangeError`.
```js
invert('red'); // 'rgba(0, 255, 255, 1)'
invert('#336699', 0.25); // 'rgba(89, 115, 140, 1)'
```
Returns `string`: The inverted color as an `rgba` string.
### lighten(color, amount)
```ts
function lighten(color: string, amount: number): string
```
Lightens a color by adding to the lightness channel in HSL space.
This is equivalent to `darken(color, -amount)`.
```js
lighten('black', 0.1); // 'hsla(0, 0%, 10%, 1)'
```
Returns `string`: The lightened color as an `hsla` string.
### mix(color1, color2, weight)
```ts
function mix(color1: string, color2: string, weight: number): string
```
Mixes two colors together using the Sass mix algorithm and returns an `rgba`
color string.
```js
mix('red', 'blue', 0.5); // 'rgba(128, 0, 128, 1)'
```
Returns `string`: The mixed color as an `rgba` string.
### opacify(color, amount)
```ts
function opacify(color: string, amount: number): string
```
Makes a color more opaque by increasing the alpha channel.
This is equivalent to `transparentize(color, -amount)`.
```js
opacify('rgba(255, 255, 255, 0.5)', 0.1); // 'rgba(255, 255, 255, 0.6)'
```
Returns `string`: The more opaque color as an `rgba` string.
### parseToHsla(color)
```ts
function parseToHsla(color: string): [number, number, number, number]
```
Parses a color into hue, saturation, lightness, and alpha channel values.
Hue is a number between 0 and 360. Saturation, lightness, and alpha are
decimal percentages between 0 and 1.
```js
parseToHsla('red'); // [0, 1, 0.5, 1]
```
Returns `[number, number, number, number]`: A tuple in the order `[hue, saturation, lightness, alpha]`.
### parseToRgba(color)
```ts
function parseToRgba(color: string): [number, number, number, number]
```
Parses a color into red, green, blue, and alpha channel values.
Reads hex (`#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`), comma-separated
`rgb()`, `rgba()`, `hsl()` and `hsla()`, CSS named colors, and
`transparent`.
This is a lenient parser, not a validator. Most strings in none of these
forms throw a `ColorError`, but not all: color names are matched by hash,
so about 3% of made-up, letters-only names are read as some color instead.
The numbers in `rgb()` and the alpha value are returned as written, without
clamping: `rgb(999, 0, 0)` gives `[999, 0, 0, 1]`.
```js
parseToRgba('rgba(255, 0, 0, 0.5)'); // [255, 0, 0, 0.5]
```
Returns `[number, number, number, number]`: A tuple in the order `[red, green, blue, alpha]`.
### readableColor(color)
```ts
function readableColor(color: string): string
```
Returns black or white, whichever has better contrast against the given
color.
```js
readableColor('white'); // '#000'
```
Returns `string`: `#000` or `#fff`.
### readableColorIsBlack(color)
```ts
function readableColorIsBlack(color: string): boolean
```
Returns whether black is the more readable color to place on top of the
input color.
This is the boolean form of `readableColor`.
```js
readableColorIsBlack('white'); // true
```
Returns `boolean`: `true` when black is the more readable foreground color.
### rgba(red, green, blue, alpha)
```ts
function rgba(red: number, green: number, blue: number, alpha: number): string
```
Builds an `rgba` color string from red, green, blue, and alpha channel
values.
```js
rgba(255, 0, 0, 1); // 'rgba(255, 0, 0, 1)'
```
Returns `string`: An `rgba` color string.
### saturate(color, amount)
```ts
function saturate(color: string, amount: number): string
```
Saturates a color by adding to the saturation channel in HSL space.
This is equivalent to `desaturate(color, -amount)`.
```js
saturate('hsl(0, 50%, 50%)', 0.1); // 'hsla(0, 60%, 50%, 1)'
```
Returns `string`: The saturated color as an `hsla` string.
### toHex(color)
```ts
function toHex(color: string): string
```
Converts a color to a hex color string.
Includes an alpha channel when the input color is not fully opaque.
```js
toHex('palevioletred'); // '#db7093'
```
Returns `string`: A hex color string.
### toHsla(color)
```ts
function toHsla(color: string): string
```
Converts a color to an `hsla` color string.
```js
toHsla('peachpuff'); // 'hsla(28, 100%, 86%, 1)'
```
Returns `string`: An `hsla` color string.
### toRgba(color)
```ts
function toRgba(color: string): string
```
Converts a color to an `rgba` color string.
```js
toRgba('midnightblue'); // 'rgba(25, 25, 112, 1)'
```
Returns `string`: An `rgba` color string.
### transparentize(color, amount)
```ts
function transparentize(color: string, amount: number): string
```
Makes a color more transparent by decreasing the alpha channel.
```js
transparentize('white', 0.1); // 'rgba(255, 255, 255, 0.9)'
```
Returns `string`: The more transparent color as an `rgba` string.
## Supported colors
color2k works in sRGB and reads the color syntax every browser has understood for years.
| Input | Examples |
| --- | --- |
| Hex | `#f00`, `#f008`, `#ff0000`, `#ff000080` |
| `rgb()` and `rgba()` with commas | `rgb(255, 0, 0)`, `rgba(255, 0, 0, 0.5)` |
| `hsl()` and `hsla()` with commas | `hsl(0, 100%, 50%)`, `hsla(0, 100%, 50%, 0.5)` |
| Named colors, in any letter case | `red`, `rebeccapurple`, `PapayaWhip` |
| `transparent` | `transparent` |
Whitespace around a color is ignored. A string in none of these forms throws a `ColorError`, with two caveats. About 3% of made-up names are read as some color, and the numbers inside `rgb()` are not range-checked or clamped. See [Check what color2k accepts](https://color2k.com/#check-what-color2k-accepts).
| Output | Returned by |
| --- | --- |
| `hsla()` string | `darken`, `lighten`, `saturate`, `desaturate`, `adjustHue`, `toHsla`, `hsla` |
| `rgba()` string | `transparentize`, `opacify`, `mix`, `toRgba`, `rgba`, and the function `getScale` returns |
| Hex string | `toHex` |
| `'#000'` or `'#fff'` | `readableColor` |
When the input is a well-formed color, you can pass these strings back in, so wrap one in `toHex`, `toRgba` or `toHsla` to get the format you want. There is one exception, under [Known edges](https://color2k.com/#known-edges): an `adjustHue` result with a negative hue. The other functions return numbers, tuples or booleans.
Not supported yet:
- Space-separated syntax such as `rgb(255 0 0 / 50%)` and `hsl(0deg 100% 50%)`.
- Percentages for alpha or for `rgb()` channels, such as `rgba(255, 0, 0, 50%)`.
- `hwb()`, `lab()`, `lch()`, `oklab()`, `oklch()` and `color()`.
### Known edges
- `hsla()` output is rounded to whole degrees and percents, so a trip to HSL and back can move a channel by a step or two. `toHex(lighten('#ffb537', 0))` is `#ffb638`. Keep the original string when you need the exact color back.
- `adjustHue` does not wrap a hue that goes below 0. When the color's own hue plus the degrees is negative, the result has a negative hue: `adjustHue('red', -120)` is `hsla(-120, 100%, 50%, 1)`. Browsers accept that, but color2k throws a `ColorError` if you pass it back in. `adjustHue('blue', -120)` is fine, because blue's hue is 240. This is a known bug. Until it is fixed, add 360 to a negative angle: `adjustHue('red', 240)`.
- Out-of-range numbers are not clamped on the way in. `rgb(999, 0, 0)` parses as written, and `getContrast` or `getLuminance` on it return numbers outside their normal range.
- Contrast functions ignore alpha. Flatten a see-through color onto its background first, as the `accessible` recipe does.
- An alpha that is not a number throws. `toRgba('rgba(1, 2, 3, .)')` throws a `ColorError`.
- `mix` always returns an `rgba()` string, even at the ends. `mix('red', 'blue', 0)` is `'rgba(255, 0, 0, 1)'`, not `'red'`.
- `getScale` returns a function, not a list of colors. Call it with numbers from 0 to 1 to get your steps.
## Recipes
Every example here runs against the built package in CI. The picture under each one is drawn from what that code returned, so the two can't disagree.
### Hover, active and focus states
Work them out from the brand color so you never hard-code them again.
```js
import { darken, readableColor, transparentize } from 'color2k';
function createTheme(brand) {
return {
brand,
brandHover: darken(brand, 0.06),
brandActive: darken(brand, 0.12),
brandSubtle: transparentize(brand, 0.88),
focusRing: transparentize(brand, 0.6),
onBrand: readableColor(brand),
};
}
const theme = createTheme('rebeccapurple');
theme.brandHover; // 'hsla(270, 50%, 34%, 1)'
theme.brandSubtle; // 'rgba(102, 51, 153, 0.12)'
theme.onBrand; // '#fff'
```
Result:
- brand: rebeccapurple
- brandHover: hsla(270, 50%, 34%, 1)
- brandActive: hsla(270, 50%, 28%, 1)
- brandSubtle: rgba(102, 51, 153, 0.12)
- focusRing: rgba(102, 51, 153, 0.4)
- onBrand: #fff
### Readable text on any background
`readableColor` answers black or white. `readableColorIsBlack` gives you the same answer as a boolean, for when you have your own ink and paper colors.
```js
import { readableColor, readableColorIsBlack } from 'color2k';
const backgrounds = ['gold', 'tomato', 'rebeccapurple', 'midnightblue'];
const labels = backgrounds.map((background) => ({
background,
color: readableColor(background),
label: background,
}));
labels[0].color; // '#000'
labels[3].color; // '#fff'
// Use your own ink and paper colors instead of pure black and white.
const text = readableColorIsBlack('gold') ? '#1a1a1a' : '#fafafa'; // '#1a1a1a'
```
Result:
- gold: #000 on gold, contrast 14.97:1 (AAA)
- tomato: #000 on tomato, contrast 7.13:1 (AAA)
- rebeccapurple: #fff on rebeccapurple, contrast 8.41:1 (AAA)
- midnightblue: #fff on midnightblue, contrast 14.85:1 (AAA)
### Contrast checks
`getContrast` returns the WCAG contrast ratio, which runs from 1 to 21 for opaque, in-range colors. `hasBadContrast` compares it to a standard: `'decorative'` (1.5), `'readable'` (3), `'aa'` (4.5, the default) or `'aaa'` (7).
```js
import { getContrast, hasBadContrast } from 'color2k';
const pairs = [
{ color: '#767676', background: 'white' },
{ color: '#999', background: 'white' },
{ color: 'gold', background: 'midnightblue' },
];
getContrast('#767676', 'white').toFixed(2); // '4.54'
hasBadContrast('#767676'); // false
hasBadContrast('#767676', 'aaa'); // true
hasBadContrast('#999'); // true
hasBadContrast('gold', 'aa', 'midnightblue'); // false
```
Result:
- Aa Text: #767676 on white, contrast 4.54:1 (AA)
- Aa Text: #999 on white, contrast 2.85:1 (fails AA)
- Aa Text: gold on midnightblue, contrast 10.59:1 (AAA)
Both functions ignore alpha and do not clamp, so give them opaque, in-range colors. A see-through color has no contrast ratio of its own, because it depends on what is behind it. `getContrast('rgb(999, 0, 0)', 'black')` is a meaningless 103.
To nudge a color until it passes AA, flatten it onto the background first. Then a see-through color is measured the way it will be seen:
```js
import {
darken,
hasBadContrast,
lighten,
parseToRgba,
readableColorIsBlack,
rgba,
toHex,
} from 'color2k';
// What `color` looks like on top of an opaque `background`.
function flatten(color, background) {
const [red, green, blue, alpha] = parseToRgba(color);
const under = parseToRgba(background);
const over = (top, bottom) => top * alpha + bottom * (1 - alpha);
return rgba(over(red, under[0]), over(green, under[1]), over(blue, under[2]), 1);
}
function accessible(color, background = '#fff') {
// Move away from the background: darker on light, lighter on dark.
const adjust = readableColorIsBlack(background) ? darken : lighten;
let result = flatten(color, background);
for (let i = 0; i < 50 && hasBadContrast(result, 'aa', background); i++) {
result = adjust(result, 0.02);
}
return toHex(result);
}
const onLight = accessible('#4dabf7'); // '#0a75cd'
const onDark = accessible('#555', '#000'); // '#787878'
const fromClear = accessible('transparent'); // '#757575'
const fromGlass = accessible('rgba(77, 171, 247, 0.5)'); // '#0b75cb'
```
Result:
- Before: #4dabf7 on #fff, contrast 2.48:1 (fails AA)
- After: #0a75cd on #fff, contrast 4.73:1 (AA)
- Before: #555 on #000, contrast 2.82:1 (fails AA)
- After: #787878 on #000, contrast 4.76:1 (AA)
- Transparent: #757575 on #fff, contrast 4.61:1 (AA)
- Half clear: #0b75cb on #fff, contrast 4.75:1 (AA)
### Color scales
`getScale` takes two or more colors and hands back a function. Give that function a number from 0 to 1 and you get the color at that point.
```js
import { getScale, toHex } from 'color2k';
const heat = getScale('#2ec4b6', '#ffd60a', '#ff3b5c');
heat(0); // 'rgba(46, 196, 182, 1)'
heat(0.5); // 'rgba(255, 214, 10, 1)'
heat(0.75); // 'rgba(255, 137, 51, 1)'
const steps = [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1].map((n) =>
toHex(heat(n))
);
steps[2]; // '#97cd60'
```
Result:
- #2ec4b6
- #62c98b
- #97cd60
- #cbd235
- #ffd60a
- #ffaf1e
- #ff8933
- #ff6248
- #ff3b5c
### Tints and shades
`mix` blends two colors. A weight of 0 is all the first color and 1 is all the second.
```js
import { mix, toHex } from 'color2k';
const base = 'rebeccapurple';
const tint = toHex(mix(base, 'white', 0.8)); // '#e0d6eb'
const shade = toHex(mix(base, 'black', 0.4)); // '#3d1f5c'
```
Result:
- tint: #e0d6eb
- base: rebeccapurple
- shade: #3d1f5c
### Tailwind palette
One color in, a 50 to 950 palette out. Use it in a Tailwind config or paste it into `@theme`.
```js
import { getScale, toHex } from 'color2k';
function palette(color) {
const scale = getScale('white', color, 'black');
const steps = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950];
return Object.fromEntries(
steps.map((step) => [step, toHex(scale(step / 1000))])
);
}
const brand = palette('#6d28d9');
brand[100]; // '#e2d4f7'
brand[500]; // '#6d28d9'
brand[900]; // '#16082b'
// Tailwind 3: tailwind.config.js
const config = { theme: { extend: { colors: { brand } } } };
// Tailwind 4: paste into `@theme { ... }`
const variables = Object.entries(brand)
.map(([step, hex]) => `--color-brand-${step}: ${hex};`)
.join('\n');
```
Result:
- 50: #f0eafb
- 100: #e2d4f7
- 200: #c5a9f0
- 300: #a77ee8
- 400: #8a53e1
- 500: #6d28d9
- 600: #5720ae
- 700: #411882
- 800: #2c1057
- 900: #16082b
- 950: #0b0416
### CSS-in-JS
This is what color2k was written for. The functions that adjust, mix and convert colors return plain CSS strings, so they drop straight into a template.
```jsx
import styled from 'styled-components';
import { darken, readableColor, transparentize } from 'color2k';
const Button = styled.button`
background: ${(props) => props.$color};
color: ${(props) => readableColor(props.$color)};
&:hover {
background: ${(props) => darken(props.$color, 0.08)};
}
&:focus-visible {
box-shadow: 0 0 0 3px ${(props) => transparentize(props.$color, 0.6)};
}
`;
const save = ;
```
Result:
- Save (default): #fff on #b3261e, contrast 6.54:1 (AA)
- Save (hover): #fff on hsla(3, 71%, 33%, 1), contrast 8.81:1 (AAA)
- Save (focus): #fff on #b3261e, contrast 6.54:1 (AA), ring rgba(179, 38, 30, 0.4)
### React
```jsx
import { useMemo } from 'react';
import { readableColor, transparentize } from 'color2k';
function Tag({ color, children }) {
const style = useMemo(
() => ({
background: color,
color: readableColor(color),
boxShadow: `0 0 0 4px ${transparentize(color, 0.8)}`,
}),
[color]
);
return {children};
}
const tags = [
New,
Sale,
Pro,
];
```
Result:
- New: #000 on tomato, contrast 7.13:1 (AAA), ring rgba(255, 99, 71, 0.2)
- Sale: #000 on gold, contrast 14.97:1 (AAA), ring rgba(255, 215, 0, 0.2)
- Pro: #fff on midnightblue, contrast 14.85:1 (AAA), ring rgba(25, 25, 112, 0.2)
### Convert between formats
```js
import { parseToHsla, parseToRgba, toHex, toHsla, toRgba } from 'color2k';
const hex = toHex('hsl(210, 100%, 50%)'); // '#0080ff'
const rgb = toRgba(hex); // 'rgba(0, 128, 255, 1)'
const hsl = toHsla(hex); // 'hsla(210, 100%, 50%, 1)'
// Need the numbers? Parse to a tuple.
parseToRgba('#0080ff80'); // [0, 128, 255, 0.5019607843137255]
parseToHsla('tomato'); // [9.130434782608695, 1, 0.6392156862745098, 1]
```
Result:
- hex: #0080ff
- rgb: rgba(0, 128, 255, 1)
- hsl: hsla(210, 100%, 50%, 1)
Going the other way, `rgba` and `hsla` build a color string from numbers:
```js
import { hsla, rgba } from 'color2k';
const glass = rgba(0, 128, 255, 0.5); // 'rgba(0, 128, 255, 0.5)'
const sky = hsla(210, 1, 0.5, 1); // 'hsla(210, 100%, 50%, 1)'
```
Result:
- glass: rgba(0, 128, 255, 0.5)
- sky: hsla(210, 100%, 50%, 1)
### Check what color2k accepts
color2k throws a `ColorError` when it can't parse a string, so a `try` tells you whether it will take one:
```js
import { ColorError, parseToRgba } from 'color2k';
function canParse(value) {
try {
parseToRgba(value);
return true;
} catch (error) {
if (error instanceof ColorError) return false;
throw error;
}
}
const inputs = ['#0d6efd', 'rgb(13, 110, 253)', 'rgb(13 110 253)', '#12345'];
const results = inputs.map((input) => [input, canParse(input)]);
canParse('#0d6efd'); // true
canParse('rgb(13 110 253)'); // false
// Loose: the shape is checked, the numbers are not.
canParse('rgb(999, 0, 0)'); // true
```
Result:
- #0d6efd: parses
- rgb(13, 110, 253): parses
- rgb(13 110 253): throws
- #12345: throws
Don't use this as a CSS validator. The parser is small and loose on purpose:
- Channel and alpha values are not range-checked. `rgb(999, 0, 0)` parses as it is written. An alpha that is not a number, such as `rgba(1, 2, 3, .)`, does throw a `ColorError`.
- Named colors are stored as hashes to save bytes, so about 3% of made-up words are accepted as if they were a color name.
If you need real validation, do it with your own rules or an allow-list before calling color2k. `CSS.supports('color', value)` won't do it either. Browsers accept forms color2k rejects, such as `rgb(13 110 253)`, so a string can pass there and still throw here.
### Invert and complement
```js
import { complement, invert } from 'color2k';
const original = '#0d6efd';
const inverted = invert(original); // 'rgba(242, 145, 2, 1)'
// The opposite side of the color wheel.
const opposite = complement(original); // 'hsla(36, 98%, 52%, 1)'
// Part of the way there. Halfway is always gray.
invert(original, 0.5); // 'rgba(128, 128, 128, 1)'
```
Result:
- original: #0d6efd
- inverted: rgba(242, 145, 2, 1)
- opposite: hsla(36, 98%, 52%, 1)
## More
- [Themes](https://color2k.com/themes.md): three theme builders that turn one color into fourteen tokens, for light or dark
- [Size](https://color2k.com/size.md): what each import costs, other libraries, and moving from TinyColor or Polished
- [Project](https://color2k.com/project.md): credits, contributing, and how releases are published