Color Name to Code
A javascript library that returns a color code for a given color name.
It supports all color names from the list of
named CSS colors from W3C.
It includes also the enum ColorName
with a full
list of all known color names.
The library can return hex color values, CSS rgb(…)
values or an array of
numeric RGB color values.
Installation
This library is published to npm registry as
color-name-to-code
.
You can install it:
npm install --save color-name-to-code
yarn add color-name-to-code
ℹ️ HINT: This library is a pure ESM package. (You may want to
read this.)
Usage
import { colorNameToCode } from 'color-name-to-code';
colorNameToCode('red');
colorNameToCode('red', { lowercase: true });
colorNameToCode('red', { short: true });
colorNameToCode('red', { hash: false });
colorNameToCode('red', { format: 'rgb' });
colorNameToCode('red', { format: 'rgb', alpha: 0.5 });
colorNameToCode('red', { format: 'array' });
colorNameToCode('"white!"');
colorNameToCode('Black');
colorNameToCode('RED');
colorNameToCode('Dodger Blue');
colorNameToCode('dark-slate-gray');
colorNameToCode('DARK_SLATE_GREY');
colorNameToCode('LeMoN cHiFfOn');
colorNameToCode('Foo Bar');
colorNameToCode(undefined);
colorNameToCode('UNKNOWN');
colorNameToCode('Foo Bar', { fallback: false });
API
colorNameToCode(name: string, options: Partial<Options>): string | [number, number, number];
Options
interface Options {
format: 'hex' | 'rgb' | 'array';
fallback: boolean;
short: boolean;
hash: boolean;
lowercase: boolean;
alpha: number;
}
-
format: 'hex' | 'rgb' | 'array'
(default: 'hex'
)
…defines the output format.
Possible values:
'hex'
defines a hex value as output format'rgb'
defines a CSS rgb(…)
value as output format'array'
defines a numeric array of RGB values as output format
-
fallback: boolean
(default: true
)
…tries to generate a color value from the given name input if a matching color
name could not be found.
To achieve this, all non-hex characters are removed from the given string and
up to the first six left characters are interpreted as hex color value.
If fallback
is false
and no matching color name is found,
colorNameToCode
will throw an error.
-
short: boolean
(default: false
)
…returns a hex value as short version if possible and set to true
.
(This option only takes effect in combination with format: 'hex'
.)
-
hash: boolean
(default: true
)
…returns a hex value with or without leading hash.
(This option only takes effect in combination with format: 'hex'
.)
-
lowercase: boolean
(default: false
)
…return a hex value with lowercase letters if set to true
.
(This option only takes effect in combination with format: 'hex'
.)
-
alpha: number
(default: 1
)
…returns a CSS rgba(…)
value with alpha value, if alpha
is lower than 1
.
(This option only takes effect in combination with format: 'rgb'
.)
License
MIT © Simon Lepel