Fork me on GitHub

colorspaces.js

A tiny jQuery and Node.js library for manipulating colors. Works as a Stylus plugin!

RGB, the color space we use here on the web is based on display technology, not human color perception. Most meaningful color operations are performed on colors in other color spaces, such as CIEXYZ or CIELUV. Read more about color spaces in my blog post.

Basic Use

colorspaces.make_color takes two arguments: the name of the color space and an array of values representing the color in the color space.

var red = $.colorspaces.make_color('sRGB', [1, 0, 0]);
var green = $.colorspaces.make_color('hex', '#00ff00');
var blue = $.colorspaces.make_color('CIEXYZ', [0.1805, 0.0722, 0.9505]);

The returned object has a method, as, that takes the name of a color space as its only argument and returns the coordinates of the color in that color space as an array.

> red.as('CIELUV')
[ 53.23288178584245, 175.05303573649485, 37.75050503266512 ]
> blue.as('hex')
'#0000ff'

These color objects also support two methods, both returning a boolean: is_displayable and is_visible. The first one determines whether the color is within the sRGB gamut and the second determines whether the color is within the CIE XYZ gamut. Note that both of these methods round the resulting values to three decimal spaces before checking whether they fit into their range; this is a useful policy because of rounding errors.

Lower Level

If you need to do many color conversions per second, you can optimize by using a low-level function converter that takes two color space names as arguments and returns a converter function.

> var conv = colorspaces.converter('CIELUV', 'hex')
> conv([53.233, 175.053, 37.75])
'#ff0000'

Stylus Support

You can use colorspaces.js in you Stylus stylesheets. From the command line, you have to run Stylus like this:

$ stylus < in.styl > out.css -u /path/to/colorspaces.js

Or if you are using it as middleware:

var colorspaces = require('colorspaces');
app.use(stylus.middleware({
  src: __dirname + '/app/views',
  dest: __dirname + '/public',
  compile: function(str, path) {
    return stylus(str)
      .set('filename', path)
      .use(colorspaces());
  }
});

Now you have access to several functions that take numerical values and return a Stylus color. All color spaces below except for hex and sRGB are supported in the Stylus plugin. The Stylus function names match the color space names.

.someclass
  color CIELCH(20.470, 74.265, 314.113)

You can still modify its opacity with Stylus’ rgba function:

.someclass
  color rgba(CIELCH(20.470, 74.265, 314.113), 0.5)

Supported Color Spaces

Download the latest colorspaces.js file from my github repo or install via npm install colorspaces.