• Stars
    star
    536
  • Rank 82,794 (Top 2 %)
  • Language
    JavaScript
  • License
    Other
  • Created over 13 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An OO-based JavaScript color parser/computation toolkit with support for RGB, HSV, HSL, CMYK, and alpha channels. Conversion between color spaces occurs implicitly, and all methods return new objects rather than mutating existing instances. Works in the browser and node.js.

onecolor

NPM version Build Status Coverage Status Dependency Status

JavaScript color calculation toolkit for node.js and the browser.

Features:

  • RGB, HSV, HSL, and CMYK colorspace support (experimental implementations of LAB and XYZ)
  • Legal values for all channels are 0..1
  • Instances are immutable -- a new object is created for each manipulation
  • All internal calculations are done using floating point, so very little precision is lost due to rounding errors when converting between colorspaces
  • Alpha channel support
  • Extensible architecture -- implement your own colorspaces easily
  • Chainable color manipulation
  • Seamless conversion between colorspaces
  • Outputs as hex, rgb(...), or rgba(...).

Module support:

  • CommonJS / Node
  • AMD / RequireJS
  • Vanilla JS (installs itself on one.color)

Package managers:

  • npm: npm install onecolor
  • bower: bower install color

Small sizes:

  • one-color.js (Basic RGB, HSV, HSL)
  • one-color-all.js (Full RGB, HSV, HSL, CMYK, XYZ, LAB, named colors, helper functions)

Usage

In the browser (change one-color.js to one-color-all.js to gain named color support):

<script src="one-color.js"></script>
<script>
  alert(
    'Hello, ' + one.color('#650042').lightness(0.3).green(0.4).hex() + ' world!'
  );
</script>

In the browser, the parser is exposed as a global named onecolor. In node.js, it is returned directly with a require of the module (after npm install onecolor):

var color = require('onecolor');
console.warn(color('rgba(100%, 0%, 0%, .5)').alpha(0.4).cssa());
rgba(255,0,0,0.4)

All of the above return color instances in the relevant color space with the channel values (0..1) as instance variables:

var myColor = color('#a9d91d');
myColor instanceof color.RGB; // true
myColor.red(); // 0.6627450980392157

You can also parse named CSS colors (works out of the box in node.js, but the requires the slightly bigger one-color-all.js build in the browser):

color('maroon').lightness(0.3).hex(); // '#990000'

To turn a color instance back into a string, use the hex(), css(), and cssa() methods:

color('rgb(124, 96, 200)').hex(); // '#7c60c8'
color('#bb7b81').cssa(); // 'rgba(187,123,129,1)'

Color instances have getters/setters for all channels in all supported colorspaces (red(), green(), blue(), hue(), saturation(), lightness(), value(), alpha(), etc.). Thus you don't need to think about which colorspace you're in. All the necessary conversions happen automatically:

color('#ff0000') // Red in RGB
  .green(1) // Set green to the max value, producing yellow (still RGB)
  .hue(0.5, true) // Add 180 degrees to the hue, implicitly converting to HSV
  .hex(); // Dump as RGB hex syntax: '#2222ff'

When called without any arguments, they return the current value of the channel (0..1):

color('#09ffdd').green(); // 1
color('#09ffdd').saturation(); // 0.9647058823529412

When called with a single numerical argument (0..1), a new color object is returned with that channel replaced:

var myColor = color('#00ddff');
myColor.red(0.5).red(); // .5

// ... but as the objects are immutable, the original object retains its value:
myColor.red(); // 0

When called with a single numerical argument (0..1) and true as the second argument, a new value is returned with that channel adjusted:

color('#ff0000') // Red
  .red(-0.1, true) // Adjust red channel by -0.1
  .hex(); // '#e60000'

Alpha channel

All color instances have an alpha channel (0..1), defaulting to 1 (opaque). You can simply ignore it if you don't need it.

It's preserved when converting between colorspaces:

color('rgba(10, 20, 30, .8)').green(0.4).saturation(0.2).alpha(); // 0.8

Comparing color objects

If you need to know whether two colors represent the same 8 bit color, regardless of colorspace, compare their hex() values:

color('#f00').hex() === color('#e00').red(1).hex(); // true

Use the equals method to compare two color instances within a certain epsilon (defaults to 1e-9).

color('#e00').lightness(0.00001, true).equals(color('#e00'), 1e-5); // false
color('#e00').lightness(0.000001, true).equals(color('#e00'), 1e-5); // true

Before comparing the equals method converts the other color to the right colorspace, so you don't need to convert explicitly in this case either:

color('#e00').hsv().equals(color('#e00')); // true

API overview

Color parser function, the recommended way to create a color instance:

color('#a9d91d'); // Regular hex syntax
color('a9d91d'); // hex syntax, # is optional
color('#eee'); // Short hex syntax
color('rgb(124, 96, 200)'); // CSS rgb syntax
color('rgb(99%, 40%, 0%)'); // CSS rgb syntax with percentages
color('rgba(124, 96, 200, .4)'); // CSS rgba syntax
color('hsl(120, 75%, 75%)'); // CSS hsl syntax
color('hsla(120, 75%, 75%, .1)'); // CSS hsla syntax
color('hsv(220, 47%, 12%)'); // CSS hsv syntax (non-standard)
color('hsva(120, 75%, 75%, 0)'); // CSS hsva syntax (non-standard)
color([0, 4, 255, 120]); // CanvasPixelArray entry, RGBA
color(['RGB', 0.5, 0.1, 0.6, 0.9]); // The output format of color.toJSON()

The slightly bigger one-color-all.js build adds support for the standard suite of named CSS colors:

color('maroon');
color('darkolivegreen');

Existing onecolor instances pass through unchanged, which is useful in APIs where you want to accept either a string or a color instance:

color(color('#fff')); // Same as color('#fff')

Serialization methods:

var myColor = color('#bda65b');

myColor.hex(); // 6-digit hex string: '#bda65b'
myColor.css(); // CSS rgb syntax: 'rgb(10,128,220)'
myColor.cssa(); // CSS rgba syntax: 'rgba(10,128,220,0.8)'
myColor.toString(); // For debugging: '[onecolor.RGB: Red=0.3 Green=0.8 Blue=0 Alpha=1]'
myColor.toJSON(); // ["RGB"|"HSV"|"HSL", <number>, <number>, <number>, <number>]

Getters -- return the value of the channel (converts to other colorspaces as needed):

var myColor = color('#bda65b');

myColor.red();
myColor.green();
myColor.blue();
myColor.hue();
myColor.saturation();
myColor.value();
myColor.lightness();
myColor.alpha();
myColor.cyan(); // one-color-all.js and node.js only
myColor.magenta(); // one-color-all.js and node.js only
myColor.yellow(); // one-color-all.js and node.js only
myColor.black(); // one-color-all.js and node.js only

Setters -- return new color instances with one channel changed:

color.red(<number>)
color.green(<number>)
color.blue(<number>)
color.hue(<number>)
color.saturation(<number>)
color.value(<number>)
color.lightness(<number>)
color.alpha(<number>)
color.cyan(<number>)    // one-color-all.js and node.js only
color.magenta(<number>) // one-color-all.js and node.js only
color.yellow(<number>)  // one-color-all.js and node.js only
color.black(<number>)   // one-color-all.js and node.js only

Adjusters -- return new color instances with the channel adjusted by the specified delta (0..1):

color.red(<number>, true)
color.green(<number>, true)
color.blue(<number>, true)
color.hue(<number>, true)
color.saturation(<number>, true)
color.value(<number>, true)
color.lightness(<number>, true)
color.alpha(<number>, true)
color.cyan(<number>, true)    // one-color-all.js and node.js only
color.magenta(<number>, true) // one-color-all.js and node.js only
color.yellow(<number>, true)  // one-color-all.js and node.js only
color.black(<number>, true)   // one-color-all.js and node.js only

Comparison with other color objects, returns true or false (epsilon defaults to 1e-9):

color.equals(otherColor[, <epsilon>])

Mostly for internal (and plugin) use:

"Low level" constructors, accept 3 or 4 numerical arguments (0..1):

new onecolor.RGB(<red>, <green>, <blue>[, <alpha>])
new onecolor.HSL(<hue>, <saturation>, <lightness>[, <alpha>])
new onecolor.HSV(<hue>, <saturation>, <value>[, <alpha>])

The one-color-all.js build includes CMYK support:

new onecolor.CMYK(<cyan>, <magenta>, <yellow>, <black>[, <alpha>])

All color instances have rgb(), hsv(), and hsl() methods for explicitly converting to another color space. Like the setter and adjuster methods they return a new color object representing the same color in another color space.

If for some reason you need to get all the channel values in a specific colorspace, do an explicit conversion first to cut down on the number of implicit conversions:

var myColor = color('#0620ff').lightness(+0.3).rgb();

console.log(myColor.red() + ' ' + myColor.green() + ' ' + myColor.blue());
0 0.06265060240963878 0.5999999999999999

Building

git clone https://github.com/One-com/one-color.git
cd one-color
npm install
npm run build

If you aren't up for a complete installation, there are pre-built packages in the repository as well as the npm package:

License

onecolor is licensed under a standard 2-clause BSD license -- see the LICENSE file for details.

More Repositories

1

knockout-dragdrop

A drag and drop binding for Knockout.
JavaScript
85
star
2

livestyle

NodeJS middleware and binary for setting up a webserver that notifies the browser of CSS updates.
JavaScript
75
star
3

gone

Golang packages for writing small daemons and servers.
Go
47
star
4

one-validation

Regexp based validation collection for common internet validation tasks
JavaScript
37
star
5

node-httperrors

Handy JavaScript Error classes representing the standard HTTP errors. Easily extensible and subclassable.
JavaScript
31
star
6

rfc2047

Encode and decode rfc2047 (MIME encoded words)
JavaScript
20
star
7

knockout.autocomplete

Auto completion binding for knockout
JavaScript
20
star
8

Ext-JS-4

Ext JS 4 checkin for patch development
JavaScript
13
star
9

knockout-transformations

Live transform methods for Knockout observable arrays
JavaScript
10
star
10

purify

Validation library for node.js
JavaScript
10
star
11

gonelog

Golang logging library
Go
9
star
12

running_sushi

Git repo tracking for distributed Chef Servers
Ruby
9
star
13

knockout-popupTemplate

A flexible, simple Knockout binding for popping up a template near an anchor element.
JavaScript
9
star
14

node-createerror

Helper for creating easily extensible and subclassable JavaScript Error classes.
JavaScript
8
star
15

Sencha-Touch

Sencha Touch checkin for patch development
JavaScript
8
star
16

knockout.list

A list binding capable of scroll through up to 500.000 items by only loading data for the viewport
JavaScript
7
star
17

poco-model

Ext JS 4 Portable Contacts data model
JavaScript
6
star
18

node-mocha-docker-postgres

Test helper for Postgres integration tests.
JavaScript
6
star
19

node-oconf

Experiments with doing cJSON with includes for configuration management
JavaScript
5
star
20

knockout-select-on-focus

This binding selects the text in a input field or a textarea when the field get focused.
JavaScript
4
star
21

ozone

Golang HTTP server/proxy daemon engine
Go
4
star
22

fluent-plugin-journal-parser

Fluentd plugin for parsing the systemd journal export format
Ruby
4
star
23

node-postgres-migrate

Postgres migrations from node.js with advisory locks.
JavaScript
4
star
24

insection

A data structure that allows efficiently to find all intervals that overlap with any given interval or point.
JavaScript
4
star
25

express-negotiator

Express/connect middleware that does HTTP content negotiation for static files
JavaScript
4
star
26

normalizeurl

Normalize urls by removing .. and . constructs, and only percent-encode the bytes that encodeURIComponent would.
JavaScript
3
star
27

teepee

Generic HTTP client
JavaScript
3
star
28

knockout-bottomsup

Knockout.js binding that keeps an element scrolled to the bottom
JavaScript
3
star
29

beanbag

Generic CouchDB driver
JavaScript
3
star
30

dislocator

Another service locator
JavaScript
3
star
31

requirejs-tpl

require.js plugin for loading templates and injecting them as <script type=text/html> elements
JavaScript
3
star
32

rfc2231

Encode and decode rfc2231/rfc5987
JavaScript
3
star
33

eslint-config-onelint-react

eslint configuration for one.com react code style
JavaScript
2
star
34

node-onedox

Source-code documenter for node.js-projects.
JavaScript
2
star
35

plack-middleware-accesslog-statsd

Log request info to StatsD
Perl
2
star
36

chef_diff

Chef context aware Git repo diff tool
Ruby
1
star
37

failboat

Failboat is the boat that transports your failures to the right destination
JavaScript
1
star
38

fromcsv

JavaScript
1
star
39

gokrb5

Thin CGO wrapper around MIT libkrb5
Go
1
star
40

action-executor

Coordinating the execution of multiple asynchronous actions in single applications.
JavaScript
1
star
41

node-dnserrors

Classes to represent DNS errors from node.js' dns module
JavaScript
1
star
42

digest

Package digest provides a drop-in replacement for http.Client that supports HTTP Digest auth for GET and POST (and other) HTTP methods
Go
1
star
43

onelint

One linter to rule them all...
JavaScript
1
star
44

eslint-config-onelint

eslint configuration for one.com javascript code style
JavaScript
1
star
45

uid-ranger

A library for parsing IMAP UID ranges
JavaScript
1
star
46

systemjs-plugin-ko-tpl

SystemJS plugin for loading Knockout.js Templates
JavaScript
1
star
47

unicoderegexp

Regular expressions matching different classes of unicode characters and some related utility functions
JavaScript
1
star