Manipulating colours in JavaScript with jColour

About one year ago, a project I was working on required me to manipulate some colours in JavaScript. At the time, I couldn’t find a library out there to help me (I don’t think the excellent xcolor existed back then) so I built a little library called jColour.

I never publicised jColour as it was never quite finished. It did what I needed it to but nothing more. As I’ve now fallen head-over-heels in love with CoffeeScript, I needed a project I could spend a few evenings working on and getting to grips with things. A rewrite of jColour fit the bill perfectly.

Everything has been rewritten entirely in CoffeeScript, the jColour documentation is generated using Docco (by the same author as CoffeeScript, Jeremy Ashkenas), and I’ve used Jasmine to write a suite of unit tests.

JavaScript is feeling hot right now. There’s some amazing tools and real innovation surfacing.

Using jColour

jColour provides a set of methods for manipulating colours, like making a colour lighter, more saturated, more transparent, etc. To start, we simply create a jColour object by passing a string to it, like this:

c = new jColour('red');
c = new jColour('#ff0000');
c = new jColour('rgba(255, 0, 0, 1));

All of the above are creating the same red coloured object. jColour will parse any recognised colour name, hex string, rgb/a or hsl/a string.

Once you have instantiated the jColour object, you can begin manipulating it. Each manipulation adjusts the jColour object and returns itself, meaning we can chain methods like this:

c.adjustHue(110).desaturate(25).darken(15);

Internally, colours are represented in both RGB and HSL format. Any colour adjustments result in both representations being recalculated. At any time we can pull the colour representation out, like so:

c.hex();    // => '#2c9c16'
c.rgb();    // => 'rgb(45, 156, 22)'
c.hsl();    // => 'hsl(110, 75, 35)'

jColour also provides more complex methods for scaling colours and mixing colours together. For full details, refer to the docs.

Colours done right

The algorithms for adjusting and converting colours are extracted from Sass and many of the manipulation methods are ported from the old Compass colors plugin.

Future plans include creating some jQuery (and possibly other framework) bindings so jColour can be used more seamlessly in jQuery projects. But as it stands, jColour is a perfectly usable library and can be integrated both in the browser or in CommonJS projects.

Oh, and did I mention, jColour is the first colour manipulation library ever to spell the word “colour” correctly. Of this, I’m proud.

Get started with jColour →

Leave a reply…

You must have JavaScript enabled in order to post comments.