README.md

Colors (RGB, HSL, objects & converters)

JS-analogue of PHP-library jzucen/colors-php.

Interfaces

Colors models

Colors models are presented in scripts ./color/<model>.js and have names like Color<MODEL>. Each model’s constructor takes color components (in the same order as in the abbreviation/table) and an optional alpha channel (defaulting to 1). Each class has parent abstract class AbstractColor stored in script ./color/abstract.js.

Common constants/preperties/methods

Common constants/preperties/methods Description
[static] readonly object MAXIMALS Maximal values for each component (minimal is always 0)
[static] readonly string MODEL_NAME Color model name (RGB for ColorRGB etc)
[static] readonly string FUNC_NAME Function name (rgb for ColorRGB etc)
[static] readonly RegExp MATCH_REGEXP Regular expression to test incoming formula value
readonly string name Returns color model’s name (class name)
object toObject () Returns object with all components and its values
static self fromObject (object object) The inverse function of toObject
string toFunc () Returns function-view - something like: rgb(…) etc
static self fromFunc (string func) Returns color instance by its function-view
object differenceFrom (self color) Calculate differences between this and an other color (in %)

ColorCMYK interface

Class ColorCMYK Description
readonly number cyan Cyan component in range [0…100]
readonly number magenta Magenta component in range [0…100]
readonly number yellow Yellow component in range [0…100]
readonly number black Black component in range [0…100]
readonly number alpha Alpha channel in range [0…1]
self setCyan (number value) Changes cyan component and returns new color
self setMagenta (number value) Changes magenta component and returns new color
self setYellow (number value) Changes yellow component and returns new color
self setBlack (number value) Changes black component and returns new color
self setAlpha (number value) Changes alpha channel and returns new color

ColorHSB interface

Class ColorHSB Description
readonly number hue Hue component in range [0…360]
readonly number saturation Saturation component in range [0…1]
readonly number brightness Brightness component in range [0…1]
readonly number alpha Alpha channel in range [0…1]
self setHue (number value) Changes hue component and returns new color
self setSaturation (number value) Changes saturation component and returns new color
self setBrightness (number value) Changes brightness component and returns new color
self setAlpha (number value) Changes alpha channel and returns new color

ColorHSL interface

Class ColorHSL Description
readonly number hue Hue component in range [0…360]
readonly number saturation Saturation component in range [0…1]
readonly number lightness Lightness component in range [0…1]
readonly number alpha Alpha channel in range [0…1]
self setHue (number value) Changes hue component and returns new color
self setSaturation (number value) Changes saturation component and returns new color
self setLightness (number value) Changes lightness component and returns new color
self setAlpha (number value) Changes alpha channel and returns new color

ColorRGB interface

Class ColorRGB Description
readonly number red Red component in range [0…255]
readonly number green Green component in range [0…255]
readonly number blue Blue component in range [0…255]
readonly number alpha Alpha channel in range [0…1]
self setRed (number value) Changes red component and returns new color
self setGreen (number value) Changes green component and returns new color
self setBlue (number value) Changes blue component and returns new color
self setAlpha (number value) Changes alpha channel and returns new color
string toHex () Converts to hexadecimal string (#RRGGB or #RRGGBBAA)
string toWeb () Converts to web-color string (Maroon, Pink etc)
static self fromHex (string hex) Creates color model instance from hexadecimal string
static self fromWeb (string name) Creates color by name (Black, Alice Blue etc)

Hexadecimal and named web colors

The ./color/hex.js module exports an object containing methods for converting RGBHEX and back.

The ./color/web.js module exports an object with named colors. The RGB color can be obtained from these names using ColorRGB.fromWeb() method (in which names are not case-sensitive and are not space/dash/underscore separators). The list of these colors is taken from wiki-page: SVG Version of X11 color names.

Common constants/properties

Common constants/properties Description
[static] readonly string MODEL_NAME Model name
[static] readonly RegExp MATCH_REGEXP Regular expression to test incoming string value
readonly string name Class name

ColorHEX interface

Instance hexColors of ColorHEX Description
string fromRgb (object rgb) Returns HEX by RGB (see object format for toRgb()
object toRgb (string hex) Returns object like { red: …, green: …, blue: …, alpha: … }

ColorWEB interface

Instance webColors of ColorWEB Description
readonly object colors All known colors: { <color name>: <hex-value>, … }
array<string> aliases (string name) Color aliases; sample "magenta"["magenta", "fuchsia"]
string toHex (string name) Returns HEX color by its web-name
string fromHex (string hex) Returns color name by HEX value
string normalizeName (string name) Converts something like Alice Bluealiceblue etc
string denormalizeName (string name) Converts name back: aliceblueAlice Blue

Web/hex colors sample

import ColorRGB from 'path/to/lib/color/rgb.js';

console.log(ColorRGB.fromWeb('Alice Blue'));
// Defined as: "aliceblue"
// Equals to: "#f0f8ff" = "rgb(240, 248, 255)"
// Console: ▶ ColorRGB {#red: 240, #green: 248, #blue: 255, #alpha: 1}

Colors factory

Instance colorsFactory of class ColorsFactory from ./color/factory.js allows to get instance of color model by string/object:

  • by formula: 'hsl(180, 0.25, 0.75)' etc;
  • by hexadecimal value: '#192837', '#a2b4c6fe' etc;
  • by web name: 'Corn Silk', 'Dark Green' etc.
  • by object: { red: 1, green: 2, blue: 3 } etc

You can substitute percentages ("10%" etc.) as values ​​in the formula

  • they will be automatically converted to the required numerical values ​​based on the MAXIMALS color model constant.

Factory interface

Constant/Method Description
[static] readonly string CMYK General name for model CMYK
[static] readonly string FUNC General name for functional view
[static] readonly string HEX General name for hexadecimal view
[static] readonly string HSB General name for model HSB
[static] readonly string HSL General name for model HSL
[static] readonly string OBJ General name for object view
[static] readonly string RGB General name for model RGB
[static] readonly string WEB General name for web-named view
[static] readonly AbstractColor[] colors All known colors
[static] readonly ColorHEX hexColors Instance of ColorHEX
[static] readonly ColorWEB webColors Instance of ColorWEB
string alias (string name) Getting a general name by its alias
AbstractColor get (string|object|AbstractColor input) Expects input string/object and creates color by it

Model names’ aliases

Each model name has aliases. All names are case insensitive. All of them can be used as target model name in the main converter.

ColorCMYK ColorFUNC ColorHEX ColorHSB ColorHSL ColorOBJ ColorRGB ColorWEB
CMYK FUNC HEX HSB HSL OBJ RGB WEB
FUNCTION HSV OBJECT NAME
FORMULA

Factory sample

import colorsFactory from 'path/to/lib/color/factory.js';

try {
  console.log(colorsFactory.get([12, 34, 56, 78]));
} catch (error) {
  console.log(error);
  // ColorsError: Type of "input" should be "string" but "array" given
}

console.log(colorsFactory.get('cmyk(12,34,56,78)'));
// ▶ ColorCMYK {#cyan: 12, #magenta: 34, #yellow: 56, #black: 78, #alpha: 1}

console.log(colorsFactory.get('#fedcba'));
// ▶ ColorRGB {#red: 254, #green: 220, #blue: 186, #alpha: 1}

console.log(colorsFactory.get('Dark Cyan'));
// ▶ ColorRGB {#red: 0, #green: 139, #blue: 139, #alpha: 1}

console.log(colorsFactory.get({ red: 1, blue: 2, green: 3 }));
// ▶ ColorRGB {#red: 1, #green: 3, #blue: 2, #alpha: 1}

try {
  console.log(colorsFactory.get('no such color'));
} catch (error) {
  console.log(error);
  // ColorsError: Container "ColorWEB" does not have a property equal to "nosuchcolor"
}

try {
  console.log(colorsFactory.get('123'));
} catch (error) {
  console.log(error);
  // ColorsError: Unable to detect handler for input "123"
}

Conversion performers

Conversion performers are presented in scripts ./converter/<source>-to-<target>.js and have names like <Source>To<Target>Converter. Each class has parent abstract class AbstractConverter stored in script ./converter/abstract.js.

Converters interface

Common preperties and methods Description
[static] readonly AbstractColor SourceClass Source color model’ class
[static] readonly AbstractColor TargetClass Target color model’ class
[static] readonly class-string<AbstractColor> SOURCE Proxy for SourceClass.name
[static] readonly class-string<AbstractColor> TARGET Proxy for TargetClass.name
static string getName (class-string<AbstractColor> source, class-string<AbstractColor> target) Constructs converter name like Source->Target
readonly string name Returns converter name created with getName ()
object toObject () Returns object { source, target }
TargetClass process (SourceClass color) Performing the conversion

Converters registry

Exports as single instance from ./converter/registry.js.

The converter registry contains a list of built-in converters (links between color models). This allows you to create a directed graph and use it to find the shortest path for converting color between models that do not have one explicit link.

The implementation of Dijkstra’s algorithm is taken (and refactored) from the dijkstrajs library repository.

The registry also allows you to register your own converters, replacing and/or supplementing the built-in ones.

The registry is an iterable object, so you can use the code:

import registry from 'path/to/lib/src/converter/registry.js';

for (const converter of registry) { /* … */ }

where converter is another converter known to the registry.

Registry interface

Method/Property Description
this add (AbstractConverter converter) Register new converter (add or replace)
AbstractConverter getByName (string name) Get converter from list by its name got by
AbstractConverter getByPath (class-string<AbstractColor> source, class-string<AbstractColor> target) Get converter from list by names of source and target color models
string getConverterName (class-string<AbstractColor> source, class-string<AbstractColor> target) Proxy to AbstractConverter.getName()
int length Count of known converters (list’ length)
array<AbstractConverter> list () List of known converters
object graph () Graph - object like: { <source1>: { <target1>: 1, <target2>: 1 } }
array<AbstractConverter> chain (class-string<AbstractColor> source, class-string<AbstractColor> target) Ordered list of converters to convert color from source to target

Converters’ facade

Exports as single instance from ./converter.js.

Facade interface

Method/Constant/Property Description
[static] readonly string CMYK Proxy to ColorsFactory.CMYK
[static] readonly string FUNC Proxy to ColorsFactory.FUNC
[static] readonly string HEX Proxy to ColorsFactory.HEX
[static] readonly string HSB Proxy to ColorsFactory.HSB
[static] readonly string HSL Proxy to ColorsFactory.HSL
[static] readonly string OBJ Proxy to ColorsFactory.OBJ
[static] readonly string RGB Proxy to ColorsFactory.RGB
[static] readonly string WEB Proxy to ColorsFactory.WEB
string|object|AbstractColor process (string|object|AbstractColor color, class-string<AbstractColor>|string target) Converts source to target
AbstractColor createColor (string|object|AbstractColor color) Proxy to ColorsFactory.get()
string getModelByAlias (string alias) Proxy to ColorsFactory.alias()
this register (AbstractConverter converter) Proxy to ConvertersRegistry.add()
AbstractConverter getByName (string name) Proxy to ConvertersRegistry.getByName()
AbstractConverter getByPath (class-string<AbstractColor> source, class-string<AbstractColor> target) Proxy to ConvertersRegistry.getByPath()
array<AbstractConverter> list () Proxy to ConvertersRegistry.list()
object graph () Proxy to ConvertersRegistry.graph()
array<AbstractConverter> chain (class-string<AbstractColor> source, class-string<AbstractColor> target) Proxy to ConvertersRegistry.chain()

For process():

  • source should be a color instance or a string with functional, hexadecimal or web-named name;
  • target should be a string cotaining color class name or be a some constant from ColorsFactory (see Model names’ aliases);
  • result will be a color instance, a string with functional, hexadecimal or web-named value or an object.

Available direct conversions

CMYK HSB HSL RGB HEX WEB FUNC OBJ
CMYK
HSB
HSL
RGB
HEX
WEB
FUNC
OBJ

All other conversions are performed by a chain of direct converters defined by Dijkstra’s algorithm.

graphviz

Magenta arrows are conversions with built-in in registry converters; Cyan arrows - with internal methods of color models.

Facade sample

import colorsConverter from 'path/to/lib/converter.js';
import ColorCMYK from 'path/to/lib/color/cmyk.js';
import ColorRGB from 'path/to/lib/color/rgb.js';

console.log(colorsConverter.process(new ColorCMYK(20, 40, 50, 80), ColorRGB.name));
// ▶ ColorRGB {#red: 40.79999999999999, #green: 30.599999999999994, #blue: 25.499999999999993, #alpha: 1}

console.log(colorsConverter.process('#c080c0', 'ColorRGB'));
// ▶ ColorRGB {#red: 192, #green: 128, #blue: 192, #alpha: 1}

console.log(colorsConverter.process(new ColorCMYK(30, 40, 50, 60), 'HSL'));
// ▶ ColorHSL {#hue: 30, #saturation: 0.16666666666666669, #lightness: 0.24000000000000002, #alpha: 1}

console.log(colorsConverter.process('Fuchsia', colorsConverter.CMYK));
// ▶ ColorCMYK {#cyan: 0, #magenta: 100, #yellow: 0, #black: 0, #alpha: 1}

console.log(colorsConverter.process({ red: 10, green: 20, blue: 30 }, 'cmyk'));
// ▶ ColorCMYK {#cyan: 66.66666666666667, #magenta: 33.333333333333336, #yellow: 0, #black: 88.23529411764706, #alpha: 1}

console.log(colorsConverter.process('#123456', 'object'));
// ▶ {red: 18, green: 52, blue: 86, alpha: 1}

Entry point

Script lib/entry.js exports 3 objects:

Object: type and name
ColorsConverter converter
ColorsFactory factory
ConvertersRegistry registry

Samples

With distributable script

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Sample [@jzucen/colors-js]</title>
    <script src="path/to/dist/colors-js.js"></script>
    <script>
      const source = ColorsJs.converter.createColor('#123456'); // or: ColorsJs.factory.get('#123456')
      const target = ColorsJs.converter.CMYK; // or: 'cmyk' etc
      const result = ColorsJs.converter.process(source, target);
      console.log(source.toObject(), target, result.toObject());
    </script>
  </head>
  <body>
  </body>
</html>

Built-in sample with ES6

# Clone the repository and navigate to its folder:
git clone git@gitflic.ru:jzucen/colors-js.git
cd colors-js

# Build, run Docker and go to its console:
make vm-build
make vm-up
make vm-console
# or copy and paste these commands from the Makefile if you don't have the make utility;
# do not use "@/usr/bin/env" unless your OS is Linux.

# Now you are in the Docker console and the following commands are executed in it.

# Start local server
make server
# Look at the URLs after the "Available on" line and open one of them in your browser.
# When finished, press "Ctrl+C" to stop the server.

# Exit the docker console:
exit

# Now you are in the main host console and the following commands are executed in it.

# Stop docker:
make vm-down

Links

Colors in Wiki

Color converters online

Конвейеры
0 успешных
0 с ошибкой