pusher.color.js
A flexible, intuitive Javascript color manipulation library

Overview

The pusher.color.js library is a Javascript library for parsing, manipulating, and formatting colors and color variations. This includes parsing all standard CSS3 color formats such as rgba(54, 128, 255, .8) and "Blue", parsing common non-web color formats such as HSV, converting betweeen formats, generating complementary colors, generating alternate tones and shades, and other generally useful functionality in dynamic, graphics intensive Javascript applications.

The library design is modelled after the excellent moment.js Javascript library for parsing, manipulating, and formatting dates.

Note: The library uses a semantic versioning scheme and is still considered an in-development API. Please feel free to use the library and report suggestions, errors, or questions; however, at this early stage of development full support and backwards compatibility can not be guaranteed.

 

Please consider donating if you find the library useful and worth supporting. Or better...

...do you have a project that Pusher, Inc. could help develop?

We're a small, but talented team devoted to high-quality, challenging creative and technical work. Please consider us!

Download v0.2.5

Production (minified) Development (full source)

Licensed under the MIT license with a sincere request for donations based on your use.

Usage

Installation

The library has no dependencies; simply include the script file in your HTML page.

Parsing

The library aims to conveniently support many different forms of color specification, so that it will work well within many host applications. See the full documentation for all support color and number formats.

Output Formats

To use a color value in an HTML page, simply specify the desired format:

More Information

The foremost goal of pusher.color is to be intuitive to use.

The basic usage should take only several minutes to learn and the rest of the functionality is intended to behave as the user would expect. Keeping the API simple and consistent is a primary goal.

Suggestions to simplify and improve the API or its documentation are always welcome.

Manipulation

The library supports many operations for manipulating a given color. Change the color saturation, reduce the amount of green, blend with another color, find the color's complement, find a different tone of the same base color, etc.

Examples

Color Variations

Generated Colors

Enter a color in the input below or click on one of the generated color swatches to generate a new set of derived colors.

Source Code


            
        

Image Modification

This example shows how to modify the color of each pixel in a given IMG element. It uses jQuery, underscore, and the HTML5 Canvas API to do the majority of the work. The color modification is within the inner loop of the pixel data modification.

Images

The original image is given at the top. The image below is dynamically generated by the script.

Example Image
Running script...

Source Code


            
        

CSS3 Formats

A pusher Color object is created by calling the pusher.color function with the color to parse. In some cases, the function can determine the color format implicitly but in others requires an explicit format argument to tell pusher.color how to parse the color data.

Implicit Formats

In the case of implicit formats, pusher.color takes a single argument containing a string representing the color. All standard CSS3 color formats are parsable as implicit color formats.

Explicit Formats

Explicit format parsing interprets the first argument as a the format to use and the following arguments represent the color description.

More Information

There are a wide variety of "fairly standard" color formats in use. Pusher.color.js generally assumes any CSS standard format in the case of ambiguity; however, by explicitly specifying the format, other formats can be used. It is never an error to explicitly specify the format to use.

Named colors

pusher.color supports all CSS3 basic color keywords and all CSS3 extended color keywords

Basic Colors

See the CSS3 basic color keywords for an official reference of all supported colors.

Extended Colors

See the CSS3 extended color keywords for an official reference of all supported colors.

Case Insensitive Parsing

Hexadecimal Format

Hex 3 Format

Hex 6 Format

Numeric RGB Format

RGB

RGBA

Numeric HSL Format

HSL

HSLA

Extended Formats

The extended color formats are formats that are not part of the CSS3 specification.

HSV Format

HSV

The percent sign is optional on the saturation and value specification.

HSVA

RGBA8 Formats

The 'rgba8' format is identical to the 'rgba' format with the exception that the alpha value (i.e. the fourth component) is specified in a 0-255 range as opposed to as a 0.0-1.0 floating point value. The 'rgb8' format is also provided and is completely identical to the 'rgb' format; it is provided simply for consistency.

RGB8

RGBA8

The rgba8 format interprets the alpha value as in the range of 0-255. For example, this is the format of the pixel data returned from a call to getImageData() on an HTML CANVAS element.

FLOAT3, FLOAT4 Formats

The 'float3' and 'float4' formats are identical to the 'rgb' and 'rgba' formats with the exception that the color values (i.e. the first through third components) are specified in a 0.0-1.0 floating point range as opposed to a 0-255 value.

Float3

Float4

Packed Integer Formats

Handles 32-bit colors packed into a single Javascript integer. Note that both signed and unsigned integers are handled correctly by pusher.color.

packed_rgba

packed_argb

Manipulation

Components

Red, Green, Blue

red(), green(), blue()

Returns the red, green, or blue component of the color as a 0-255 value.

red(value), green(value), blue(value)

Sets the red, green, or blue component of the color. Expects a value in the range 0-255.

red('op value'), green('op value'), blue('op value')

Modifies the red, green, or blue components of the color. Valid ops are +, -, *, +=, -=, *=. In the case of the operands with an = the color is modified in place; otherwise, a copy of the color is made and a new modified color is returned.

Hue, Saturation, Value

hsv(), hsva()
hue(), saturation(), value()

hue('op value'), saturation('op value'), value('op value') hue('op', value), saturation('op', value), value('op', value)

Alpha

alpha(), alpha8()

The alpha() method returns the alpha value of the color in the standard CSS3 0.0-1.0 range. The alpha8() method returns the alpha value in the 0-255 range (note: the "8" comes from the 'rgba8' format, where the 8 is the number of bits used per channel to store the color).

Luminance

luminance(), luminance8(), luminanceFast(), luminanceFast8()

The luminance() method returns the luminance of the RGB color based on a non-linear scaling as based on the W3C css color definition.

The luminanceFast() method returns the luminance of the RGB color based on simple biased weighting of 0.2126, 0.7152, 0.0722.

Grayvalue

grayvalue(), grayvalue8()

The grayvalue() method returns the unweighted average of the RGB color.

Operations

tint(amount)

A tint is a color with white mixed into it.

Amounts may be specified as a floating point value, a parseable floating-point string, or as percentages.

shade(amount)

A shade is a color with black mixed into it.

tone(amount)

Tone is a color with gray mixed into it.

blend(color, amount)

The blend operation linearly mixes two colors by their RGBA component values. An input of 0 will result in an unmodified copy of the first color whereas an input of 1 will result in a unmodified copy of the second color.

In keeping with much of the API, the blend can be specified as a percentage as well. Also note the first color argument will be parsed as a color object if it is not already one.

add(), subtract(), multiply()

Component-wise operations on the colors. The operations use a floating point color component representation that, for example, would mean a red multipied by a grey becomes darker, not brighter.

The aliases sub and mul are also available.

inc(), dec()

These methods work just like add() and subtract() except that they modify the calling object.

scale(factor)

Multiplies each color component by a uniform scale factor.

The scale factor does not apply to the alpha channel.

xor(color)

Treats the two colors as bitfields and applies an XOR operation to the red, green, and blue components.

Note: the XOR is not applied to the alpha component and the source color's alpha is copied directly to the resulting color.

clamp()

Clamps the internal representation of the color to a displayable range. This method is not often necessary to call explicitly, but may be desired as an intermediate operation when values are known to exceed displayable range and the excess range is not desired for subsequent operations.

complement()

Returns the color opposite in hue on the color wheel. This is effectively equivalent to color.hue('+180').

The compliment of a color's complement is always the original color.

triad()

Returns a set of three colors including the color itself and the two colors to 120 degrees to the left and right of it on the color wheel. Effectively equivalent to [ color, color.hue('-120'), color.hue('+120') ].

hueSet()

Returns a set of nine colors of varying saturation and value all with the source color's hue. Useful for generating a set of distinguishable, but similar colors.

Example: hueSet #08C

hueRange(range, count)

Returns a set of count colors evenly spaced along a range in hue. The range determines how many degrees to vary from the hue in both directions, resulting in a total span of 2 * range.

Example: hueRange orange 20°

Contrast Colors

contrastWhiteBlack()

For dark colors, returns white and for bright colors, returns black. This can be useful for choosing a background color for an arbitrary color.

contrastGray()

Returns a grayscale equivalent of the color that differs in value by 30% in order to make it clearly distinguishable from the source color. This can be useful for border colors or other subtly different contrast colors.

Conversions

HTML Format

html()

Converts the color to a string format parsable by a CSS3-compliant web browser.

Note: the implementation does not guarentee which format will be used for output by html(). If a specific format is required, use an explicit call for that particular format.

html(format)

Converts the color to a string format parsable by a CSS3-compliant web browser. Note that only CSS3 format types as available (e.g. html('hsv') is not a supported format type). The resulting color is always the nearest match in case of inexact matches and the alpha value is dropped from formats not supporting alpha.

html('keyword')

The 'keyword' will find the nearest match for the color in RGB space. This is implemented with as an O(N) algorithm; and thus is not very efficient.

Hexidecimal Format

hex3(), hex6()

Alpha values are not supported by this format and are implicitly dropped during the conversion.

RGBA8 Format

rgb8(), rgba8()

These methods return the color as an array of 0-255 ranged color components. The rgba8() format is the format used internally for pixels in CANVAS elements and can be useful for manipulating canvas pixel colors.

FLOAT3, FLOAT4 Formats

float3(), float4()

Packed Formats

packed_rgba(), packed_argb()

These methods return the color as a single packed, unsigned integer. (The demo below displays the results as a hexidecimal string as well simply for the convenience of the reader.)

Development

MIT License

The pusher.color.js library is released under the MIT License

The license is an extremely lenient license. Please feel free to use the library in any manner you wish that is in conformance with the license. Contributions in the form of defect fixes, new features, code improvements, feedback & suggestions, and donations are always welcome but never required.

Please contact us at any time.

Credits & Acknowledgements

Special thanks to moment.js for the inspiration for a clean, well-documented API.

Thanks to...

Acknowledgement as goes to the W3C for making public standards of the various color specifications this library uses. Openly available standards and specifications are good things.

The technology used to create and/or influenced the creation of the library and this web page includes jQuery, underscore.js, Twitter Bootstrap, google-code-prettify, Twig and many others. All of the aforementioned are recommended as useful tools.

Version History

==== Version 0.2.5 ==== * Released 2013.10.09 * Download [pusher.color.js](https://bitbucket.org/pusherhq/pusher.color/raw/v0.2.5/lib/pusher.color.js) * -- Code Changes -- * Add contrastText() method * Updated luminance() to account for non-linear sRGB gamut * Added luminanceFast() for the "old" calculation ==== Version 0.2.4 ==== * Released 2013.03.29 * Unit tests: 543/543 * Download [pusher.color.js](https://bitbucket.org/pusherhq/pusher.color/raw/v0.2.4/lib/pusher.color.js) * -- Code Changes -- * Add inc() and dec() methods * Added new unit tests ==== Version 0.2.3 ==== * Released 2013.03.26 * Unit tests: 461/461 * Download [pusher.color.js](https://bitbucket.org/pusherhq/pusher.color/raw/v0.2.3/lib/pusher.color.js) * -- Code Changes -- * Converted project to NPM & bower compatible package * Added new unit tests ==== Version 0.2.2 ==== * Released 2013.03.24 * Unit tests: 244/244 * -- Code Changes -- * Fix for HSL parsing code. Improperly setting value to floor. ==== Version 0.2.1 ==== * Released 2012.10.08 * Production size: 13.0k/4.5k Unit tests: 241/241 * -- Code Changes -- * Fix Firefox-specific defect with regular expression. Thanks Thomas Hoppe for reporting the error. Thanks to [mrrena's blog](http://mrrena.blogspot.com/2009/02/invalid-range-in-character-class.html) helping elucidate the issue and fix. ==== Version 0.2.0 ==== * Released 2012.09.08 * Download [production](/pusher/js/pusher.color-0.2.0.min.js) / [development](/pusher/js/pusher.color-0.2.0.js) * Production size: 12.9k/4.5k Unit tests: 241/241 * -- Code Changes -- * Changed internal format to floating-point * Added luminance8(), grayvalue8() * Changed lumninance(), and grayvalue() to return a 0.0-1.0 ranged value * Added add() method * Added subtract() method * Added multiply() method * Added xor() method * Added clamp() method ==== Version 0.1.4 ==== * Released 2012.09.08 * Download [production](/pusher/js/pusher.color-0.1.4.min.js) / [development](/pusher/js/pusher.color-0.1.4.js) * Production size: 12.7k/4.4k Unit tests: 229/229 * -- Code Changes -- * Minor internal changes for better performance ==== Version 0.1.3 ==== * Released 2012.08.09 * Download [production](/pusher/js/pusher.color-0.1.3.min.js) / [development](/pusher/js/pusher.color-0.1.3.js) * Production size: 12.2k/4.2k Unit tests: 229/229 * -- Code Changes -- * Add support for packed_rgba format * Add support for packed_argb format

Version 0.1.2

Version 0.1.1

Version 0.1.0

Unit Tests

The unit tests are available via the NPM package. They use the nodeunit testing framework. To run the tests, simply run

$ nodeunit test

in the base pusher.color directory.