Coder Social home page Coder Social logo

color's Introduction

color

JavaScript library for immutable color conversion and manipulation with support for CSS color strings.

const color = Color('#7743CE').alpha(0.5).lighten(0.5);
console.log(color.hsl().string());  // 'hsla(262, 59%, 81%, 0.5)'

console.log(color.cmyk().round().array());  // [ 16, 25, 0, 8, 0.5 ]

console.log(color.ansi256().object());  // { ansi256: 183, alpha: 0.5 }

Install

$ npm install color

Usage

const Color = require('color');

Constructors

const color = Color('rgb(255, 255, 255)')
const color = Color({r: 255, g: 255, b: 255})
const color = Color.rgb(255, 255, 255)
const color = Color.rgb([255, 255, 255])

Set the values for individual channels with alpha, red, green, blue, hue, saturationl (hsl), saturationv (hsv), lightness, whiteness, blackness, cyan, magenta, yellow, black

String constructors are handled by color-string

Getters

color.hsl();

Convert a color to a different space (hsl(), cmyk(), etc.).

color.object(); // {r: 255, g: 255, b: 255}

Get a hash of the color value. Reflects the color's current model (see above).

color.rgb().array()  // [255, 255, 255]

Get an array of the values with array(). Reflects the color's current model (see above).

color.rgbNumber() // 16777215 (0xffffff)

Get the rgb number value.

color.hex() // #ffffff

Get the hex value. (NOTE: .hex() does not return alpha values; use .hexa() for an RGBA representation)

color.red()       // 255

Get the value for an individual channel.

CSS Strings

color.hsl().string()  // 'hsl(320, 50%, 100%)'

Calling .string() with a number rounds the numbers to that decimal place. It defaults to 1.

Luminosity

color.luminosity();  // 0.412

The WCAG luminosity of the color. 0 is black, 1 is white.

color.contrast(Color("blue"))  // 12

The WCAG contrast ratio to another color, from 1 (same color) to 21 (contrast b/w white and black).

color.isLight();  // true
color.isDark();   // false

Get whether the color is "light" or "dark", useful for deciding text color.

Manipulation

color.negate()         // rgb(0, 100, 255) -> rgb(255, 155, 0)

color.lighten(0.5)     // hsl(100, 50%, 50%) -> hsl(100, 50%, 75%)
color.lighten(0.5)     // hsl(100, 50%, 0)   -> hsl(100, 50%, 0)
color.darken(0.5)      // hsl(100, 50%, 50%) -> hsl(100, 50%, 25%)
color.darken(0.5)      // hsl(100, 50%, 0)   -> hsl(100, 50%, 0)

color.lightness(50)    // hsl(100, 50%, 10%) -> hsl(100, 50%, 50%)

color.saturate(0.5)    // hsl(100, 50%, 50%) -> hsl(100, 75%, 50%)
color.desaturate(0.5)  // hsl(100, 50%, 50%) -> hsl(100, 25%, 50%)
color.grayscale()      // #5CBF54 -> #969696

color.whiten(0.5)      // hwb(100, 50%, 50%) -> hwb(100, 75%, 50%)
color.blacken(0.5)     // hwb(100, 50%, 50%) -> hwb(100, 50%, 75%)

color.fade(0.5)     // rgba(10, 10, 10, 0.8) -> rgba(10, 10, 10, 0.4)
color.opaquer(0.5)     // rgba(10, 10, 10, 0.8) -> rgba(10, 10, 10, 1.0)

color.rotate(180)      // hsl(60, 20%, 20%) -> hsl(240, 20%, 20%)
color.rotate(-90)      // hsl(60, 20%, 20%) -> hsl(330, 20%, 20%)

color.mix(Color("yellow"))        // cyan -> rgb(128, 255, 128)
color.mix(Color("yellow"), 0.3)   // cyan -> rgb(77, 255, 179)

// chaining
color.green(100).grayscale().lighten(0.6)

Propers

The API was inspired by color-js. Manipulation functions by CSS tools like Sass, LESS, and Stylus.

color's People

Contributors

andsnpl avatar ben-eb avatar buzuosheng avatar chapuzzo avatar dliv avatar egeriis avatar fuzhenn avatar harthur avatar headwindz avatar iamstarkov avatar ianstormtaylor avatar kristoferjoseph avatar michaeljones avatar moox avatar qix- avatar robertfischer avatar sderosiaux avatar shfshanyue avatar slaweet avatar technobuddha avatar toinane avatar tsdorsey avatar victorteokw avatar vyushin avatar welll avatar wmira avatar wtho avatar zdenekkostal avatar zenflow avatar zubb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

color's Issues

mix().string() is giving me invalid rgb strings

When i call Color('#eb710c').mix(Color('black'), 0.9).string() i get rgb(66.6, 134.1, 175.5) which is an invalid css property, because of the dots.
I don't think this is the expected result and it returned integers before the 1.x update. But if it is, is there an easy way to get integer rgb values?

Eslint

Is it worthwhile setting up eslint to catch formatting inconsistencies?

v0.7.1 conflicts with html5 canvas drawn objects, v0.4.1 doesn't

I've tested with color-0.4.1.min.js and this works nicely with html5 canvas objects (context.rect(x, y, w, h)).

When replacing with color-0.7.1.min.js, objects on the html5 canvas get distorted. So the color script somehow conflicts with the drawing of objects on the html5 canvas.

Lightness manipulation methods fail on color('black'), except negate()

Hi, color team. This lib is great, and seems to work normally... except on any version of the color black.

On black, if I try to lighten it, nothing changes. lighten(0.5) and whiten(0.5) fail completely on black, where they work fine on other colors, or on grey. And darken() works fine on white. It's just black that fails. (And I'm baffled by the results of lightness(0.5), but that might be more a question of my understanding. :-)

negate() works, and converts it to white. alpha(0.5) works.

mix() also seems to work on black.

I've tried hard to test this thoroughly. You can see a series of experiments on this Tonic, and you can manipulate the 'source' color to see the varying results: https://tonicdev.com/xmlilley/testing-color-lib

Please let me know if I'm somehow just misunderstanding either color-theory or the API. It's certainly possible. If nothing else, this behavior is at least violating the principle-of-least-surprise for me. :-)

Is this project active, and are you taking PR's for the current branch, or only for your 1.0 milestone?

instanceOf checking

Since the module exports a factory function instead of a constructor, there's no easy way to get the constructor to do an instanceof check against it. Is there any way you could expose the constructor object as well, to make this possible?

Remove bower & component.json or automate version bump

Version in bower.json & component.json is clearly outdated.

Any watchers who still use bower or component(1) ?
Otherwise I'm wondering if we should just stop supporting this 2.
I think this 2 packages managers can use package.json, do they?

Complement function?

ie. given a background color what's the appropriate foreground color and vise versa

Bad CMYK

var c = new Color('black');
c.cmyk(); //{c: NaN, m: NaN, y: NaN, k: 100}

:(

rgb2hsl bug

compass will translate rgba(#F1F1F1, .9) into rgba(241, 241, 241, 0.9), and cssnano will compress it into hsla(0,0%,95%,.9).

However, rgb(241, 241, 241) actually equals hsl(0,0%,94.5%). So I think cssnano (Qix-.color) rounded it up, but it will result in UI bug, though minor.

var Color = require('Color');
Color('rgba(241,241,241,.9)').hslString()
/// hsla(0, 0%, 95%, 0.9)'

downstream issue: cssnano

Cannot install through bower

When attempting to install through bower, I get the following error. The package also does not yet use bower.json.

$ bower install --save harthur-color
bower not-cached    git://github.com/harthur/color.git#*
bower resolve       git://github.com/harthur/color.git#*
bower checkout      harthur-color#master
bower deprecated    Package harthur-color is using the deprecated component.json
bower invalid-meta  color is missing "ignore" entry in bower.json
bower resolved      git://github.com/harthur/color.git#f4f88a5b9b
bower ENOTFOUND     Package harthur/color-convert=harthur/color-convert not found

Add lab space

There are nice Lab space conversion functions in color-convert (rgb2lab, lab2rgb, etc.). But the Lab space isn’t in color.js.
Maybe it’s worth adding that API to the color? L-channel can be named 'L' not to interfere with hsl lightness, which is lower-case 'l'. Same with 'A' and 'B'.

What is the reason Lab is excluded from the color? @MoOx @harthur.

What is possible workaround for that if Lab isn’t going to be included into color?

Switching spaces change value (rounding ?)

var c = Color('#123456');
console.log(c.saturationv(), c.hexString());
// -> 79 #123456

c.saturationv(79);
console.log(c.saturationv(), c.hexString());
// -> 79 #123457

// Should be '79 #123456'

requirebin

Hi !
I've encountered cases where initializing a color with hexstring and setting its component from another space (hsv) can result in a different hexstring even if the values are set to be the same as before.
I'm guessing the culprit is not in color but maybe in color-convert? Is there a way to avoid those differences ?

Thanks for this nice library :)

Not an issue, a question re: require()

First off, this is truly awesome code, very clearly written, and I hope to crib some of its style (if not substance) in other work I am doing.

Second, in the "browser" version, I see reference right up at the top to

require("color-convert")

and the like. I am of the opinion that require is a Node thing, not part of the JavaScript language. Is my impression wrong? If not, how does this work in a non-node setting? I don't see require() defined anywhere in the code.

Thanks again for writing this!

Walter

Browser build v0.4.4

Hi,

Could we get a browser build for v0.4.4, currently can only download v0.4.1.

Many thanks.

Color.clone doesn't create equal object

var c1 = new Color();
var c2 = c1.clone();
expect(c1).toEqual(c2); // => false

I tracked it down, and it's the hsw string that doesn't match:

c1.hwbString() // => hwb(0, 0%, 100%)
c2.hwbString() // => hwb(0, 0%, 0%)

Make Color objects immutable

Making Color objects immutable would result in a leaner API:

// Mutable
const red = Color('#ee1100')
const darkerRed = red.clone().darken(.2)
const lighterRed = red.clone().lighten(.2)
// Immutable
const red = Color('#ee1100')
const darkerRed = red.darken(.2)
const lighterRed = red.lighten(.2)

Luminosity function overwrites the RGB array

When calling the luminosity method, the rgb values are changed.

Check out this bin to see it live:
http://jsbin.com/uputev/1/edit

Possible solution:
In luminosity method instead of:

var rgb = this.values.rgb; do
var rgb = [this.values.rgb[0], this.values.rgb[1], this.values.rgb[2]] so rgb will be not the original array/object and it don't gets modified.

Add schemas

color-js has schema support (schemaFromDegrees). Are you planning to add this your library? Based on your api it seems trivial to implement.

Initializing from HSL and HWB producing different values

Hello, ran into this when trying to get a CSS keyword from an object initialized using HSL or HWB notations.

var c1 = new Color('brown');
var c2 = new Color('hsl(0, 59%, 41%)');
var c3 = new Color({h: 0, s: 59, l: 41});

On the first case, converting it to HSL will give the right result:

c1.hslString();
// "hsl(0, 59%, 41%)"

Trying to convert the other two won't work:

c2.keyword();
// undefined
c3.keyword();
// undefined

Comparing the RGB values you can see they are different which makes the keyword method fail:

c1.rgb();
// {r: 165, g: 42, b: 42}

c2.rgb();
// {r: 166, g: 43, b: 43}

c3.rgb();
// {r: 166, g: 43, b: 43}

Repeatedly calling rgbaArray appends to the inner rgb array.

Same issue for hslaArray as well. For example:

> var c = new Color()
> c.rgbaArray()
[0, 0, 0, 1]
> c.rgbaArray()
[0, 0, 0, 1, 1]
> c.rgbaArray()
[0, 0, 0, 1, 1, 1]
> c.rgbaArray()
[0, 0, 0, 1, 1, 1, 1]

rbgaArray should always return a 4 element array. You can fix by using concat instead of push.

Cater for opacity when converting to hex string

It seems opacity gets ignored when converting a color to hex value.

For example, passing in: var color = Color("rgba(0, 0, 0, 0.8)");

and then converting that to a hex value via color.hexString(); returns #000000 whereas it actually renders as #cbcbcb in the browser?

HSL percentage properties should be modify by percent as is

Hi everybody,

I have a problem.

For example,

darken(0.15) == sass or less darken(15%)
lighten(0.3) == sass or less lighten(30%)

At the moment we have:

darken(0.15) == current percent - current percent * 0.15
lighten(0.3) == current percent + current percent * 0.3

Why do you multiply percent with another form of percent?

https://github.com/sass/libsass/blob/267df0d59e084363b0da764e0b2126e7e45a92bb/src/functions.cpp#L491
As you can see lighten or darken functions do simple arithmetics.

darken(0.15) == current percent - 15%
lighten(0.3) == current percent + 30%

I think we should unify that functions to prevent misunderstandings.

What do you think about it?

'.mix()' method fails to work with cloned color

Hi there!

First of all I would like to excuse for test case that is not as simple as it should be.

I have next code

        ...
        //var baseColor = Color('#73FF73');
        var gtColor = Color('#FF7400');
        var ltColor = Color('#004DFF');
        var colors = { '0.00': 'rgb(255,255,255)' };

        this.getDepDataSet().forEach(function(item) {
            if (typeof colors[item.index] !== 'undefined') {
                return;
            }

            var value = item.number;
            var otherColor = value > 1 ? gtColor : ltColor;
            var weight = (value > 1 ? (value - 1) : (1 - value)) * 3;
            //var resultColor = baseColor.clone().mix(otherColor, weight);
            var resultColor = Color('#73FF73').mix(otherColor, weight);
            colors[item.index] = resultColor.rgbString();
        });
        ...

Code above produces a set of colors that are used in table coloring.
With this code I get a right colors that I am expect (lets call them 'correct'). See 1st pic. When I use code that is commented I get wrong colors (see 2nd pic). In both cases same set of data is used

2015-01-09-212715_1920x1080_scrot

2015-01-09-213757_1920x1080_scrot

support hwb()

I'm using myth (that use rework-color-function (that use css-color-function (that use your module))) & I'll be happy to get hwb() support.
I'll see if I can make a pr quickly.

Conversion from rgbNumber back to color

color.rgbNumber() returns an integer, however, there is no setter Color().rgbNumber(int) that takes this integer to convert back to color.

What's the best way to do a round-trip for rgbNumber?

Replace max values by modulo for degree

(I'm on a PR to add hwb() & found a bug that will be fixed by it - capping must be set for the current space prior making the loop for conversion).

0deg == 360deg right ?
So if we tolerate a maximum of 360, we have inconsistent results when converting + capping values. color-convert converts 360 to 0 so we have hue() returning 360 or 0 depending on the method we use. If I set hwb using 400, I get 360, but using hue() I get 0 cause its using hsl space (that has been converted by color-convert).

Should we stop using max for hue & use a modulo (or nothing). Cause hsl(720deg,..) is valid.
Not sure how to handle that.

Note: for my current PR I'll change max to 359 to be coherent with the "max" approch.

Green lighten to 1 is green

(new Colour('red')).lighten(1).rgb()
Object {r: 255, g: 255, b: 255}
(new Colour('blue')).lighten(1).rgb()
Object {r: 255, g: 255, b: 255}
(new Colour('green')).lighten(1).rgb()
Object {r: 0, g: 255, b: 0}

Why mix function doesn't work here?

This library is really weird, mutability is causing me so many problems :(

But anyway, why this piece of code:

var color = require("color")
const b = color('#fff')
console.log(b.clone().mix(color('black')).hexString())

returns "#000000" ? it doesn't make any sense. If i remove clone() it works.

In fact:

console.log(color('#ffffff').clone())
Color
values: Object
alpha: 1
cmyk: [0, 0, 0, 0]
hsl: [0, 0, 0]
hsv: [0, 0, 0]
hwb: [0, 0, 0]
rgb: [0, 0, 0]

Why should I use it?

Hi. I found it in Google and I have a question - why should I use it instead of color-js (which as you said was inspiring you). What was wrong with color-js that you decided to write your own library? I ask, becouse your lib has much more followers and less capabilities.

Calling color breaks in io.js v2.4.0 (npm v2.13.0)

Hi,

Calling the color node module seems to break things in io.js and possibly npm 2.13.0. This is before I even try to use any of its functionality, just calling the module like so triggers the following error:

import Color from 'color'

I tried uninstalling and reinstalling it. Here is the error message:

ERROR in ./~/color/~/color-string/~/color-name/index.json
Module parse failed: /Users/~/git/xyz-repo/node_modules/color/node_modules/color-string/node_modules/color-name/index.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
|   "aliceblue": [240, 248, 255],
|   "antiquewhite": [250, 235, 215],
|   "aqua": [0, 255, 255],
 @ ./~/color/~/color-string/color-string.js 2:17-38

Any help on this would be really appreciated it.

Bad hslString

var c = new Color;
c.value(0);

c.hslString() //"hsl(0, NaN%, 0%)"

:(

Update built color.js

The gh-pages branch contains a built version of color.js for browsers. However this file wasn't updated against the last version of the lib (0.5.0).

Conflict

Hi,
Just a heads up -
I wanted to try your script with the ColorPicker in Wordpress called Iris. However, there appear to be naming conflicts, because when I import it, it breaks Iris. This might be a common use-case for your script, so I thought you should know.

http://automattic.github.com/Iris/

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.