Giter VIP home page Giter VIP logo

one-com / one-color Goto Github PK

View Code? Open in Web Editor NEW
532.0 33.0 40.0 4.06 MB

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.

License: Other

JavaScript 64.67% CSS 17.62% HTML 17.71%

one-color's Introduction

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.

one-color's People

Contributors

alexjeffburke avatar arcanis avatar christophe-ledu avatar darekkay avatar dependabot[bot] avatar jonathanolson avatar lipis avatar munter avatar pablosichert avatar papandreou avatar ryanramage avatar x09326 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  avatar  avatar  avatar  avatar

one-color's Issues

Remove publishConfig from package.json

The package.json for this node module currently includes a publishConfig section indicating that the package should be published to the public NPM registry. This makes it somewhat difficult to push this package to another feed.

I believe that if the publishConfig section isn't present npm will automatically push it to the public registry, unless otherwise specified, so removing it shouldn't hurt anyone.

Would it be possible to remove the publishConfig section from the package.json?

About the source map files

Hi, I'm going to host this lib on cdnjs.
But I meet some problems.

I send a pull request to cdnjs. cdnjs/cdnjs#7878
But the map files (one-color-all.map and one-color.map) look strange.
Can you explain or check it?
Because I don't know very much about js and map file.
I hope I can learn some information from here, and send the pull request successfully.

Thank you.

Module not found: Error: Can't resolve 'ONECOLOR'

Hello,

I posted this issue over on colorjoe but it seems to be a bit quiet over there.

Steps to reproduce:

my_entry_file.js:

import onecolor from './one-color';
import colorjoe from './colorjoe';

webpack.config.js

entry: "./src/js/my_entry_file.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist/js")
},

When running webpack, I get error:

ERROR in ./src/js/colorjoe.js
Module not found: Error: Can't resolve 'ONECOLOR' in 'C:\Users\Me\Documents\my_repo\src\js'
 @ ./src/js/colorjoe.js 9:8-11:10

The relevant files used are:

https://github.com/One-com/one-color/blob/master/one-color.js

https://github.com/bebraw/colorjoe/blob/master/dist/colorjoe.js

[ Note: later in this thread I switched to using the files in the colorjoe /src folder ]

Accept non-padded hex

It would be a bit easier to use the API if you would allow non-padded hex (ie. #abcd would be treated as #abcd00).

Is there some specific reason why there has to be hash in front of a hex btw?

In case jQuery exists, window.one.color is not set

Hi,

Looks like in case jQuery exists, one.color doesn't set up a global. This in turn causes colorjoe to fail. Any thoughts on this issue? Would it make sense to have it available as a global in any case? Alternatively I could try to detect this special case and solve it on my end.

can't build the lib

if I run make clean and then make all it fails saying

/bin/sh: 1: flattenOneInclude: not found
make: *** [one-color-debug.js] Error 127
flattenOneInclude lib/color/_base.js > one-color-debug.js

I installed assetgraph and it doesn't seem to fix it.

Output as 'hsv(...)'

Feature list in documentation states:
"Outputs as hex, rgb(...), rgba(...) or hsv(...)"

How do I output as hsv(...) ?

Named colors?

You add named color parsing to this and this thing is golden.

color mixing

it would be nice to be able to mix colors:

color.prototype.mix = function(other, amount) {
  amount == null || amount = 0.5
  // etc
} 

Validate is string a color

Hi

Is it possible to validate does string represents a valid color value?

I guess lib somewhere makes internally such validation to avoid trying manipulating non-color values, but I wasn't able to find it. If such method indeed exists, it would be great if it would be exposed for public use.

Parsing CMYK percentages

Hi,

Imagemagick can output CMYK in the following format:

$ convert 9999716688CX.EPS -scale 1x1\! -format 'average_color::: %[pixel:u]' info:-
cmyk(1.95468%,3.82086%,5.06294%,11.3802%)

Passing that to onecolor 2.4.2, gives:

      hex = onecolor("cmyk(1.95468%,3.82086%,5.06294%,11.3802%)").hex();
                                                                  ^
TypeError: Object false has no method 'hex'

Ideally, I could pass the cmyk(1.95468%,3.82086%,5.06294%,11.3802%) string straight into one-color without having to do any conversion on it myself first.

Any chance a future version of one-color might support that?

RGBA() like color parsing problem

Color like "rgba(0,0,0,.16)" get its alpha part divided by 255 and it should not be as it it a value between 0 and 1 in that case.

Dropping 2nd clause in the license?

Hi.

The 3-clause BSD license you use is generally deemed incompatible with GPL, as it contains "advertising" clause:

Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.

Any chance of switching to 2-clause BSD?

Unnamed AMD module

The AMD module defined in color.js is unnamed:

define(function () {
    return ONECOLOR;
});

However, this makes AMD loading incompatible with tools like Ember CLI. For example, this issue. I understand there are some benefits to an unnamed module because you can use it anywhere under different names. However, would you be open to using a named module or allowing the developer to set the module name somewhere? In either case, the production code would resemble something like:

define('one-color', [], function () {
    return ONECOLOR;
});

Check that object is an instance of (any) Color

It's possible to check if an object is an instance of RGB/HSV/HSL/...

obj instanceof one.color.RGB

However how to test that object is simply a color (the onecolor API is available), without checking for all color types?

Eliminate color-namedColors.js in favor of DOM based solution?

Hi,

It looks like it might be possible to eliminate the lookup you have at color-namedColors.js by calculating the color via DOM. You simply have to create a dummy element and set its CSS color with the given name. After that you can fetch the real value.

I'm not sure how well this works cross-browser. In case you are interested in slimming down the library, I guess this is something you might want to investigate.

Add new csswg color specification drafts to accepted syntaxes

Updated syntages for rgb/rgba:

<dfn>rgb()</dfn> = rgb( <<rgb-component>>{3} [ / <<alpha-value>> ]? ) | rgb( <<rgb-component>>#{3} , <<alpha-value>>? )
 <dfn>rgba()</dfn> = rgba( <<rgb-component>>{3} [ / <<alpha-value>> ]? ) | rgba( <<rgb-component>>#{3} , <<alpha-value>>? )

similar for hsl/hsla:

<dfn>hsl()</dfn> = hsl( <<hue>> <<percentage>> <<percentage>> [ / <<alpha-value>> ]? ) | hsl( <<hue>>, <<percentage>>, <<percentage>>, <<alpha-value>>? )
<dfn>hsla()</dfn> = hsla( <<hue>> <<percentage>> <<percentage>> [ / <<alpha-value>> ]? ) | hsla( <<hue>>, <<percentage>>, <<percentage>>, <<alpha-value>>? )

Also worth noting: ''hsl()'' and ''hsla()'' functions now accept <<angle>> as well as <<number>> for hues

See w3c/csswg-drafts@a54f8b2

LAB incorrectly converted

LAB colour: 60, -28, -32
RGB (converted): 0, 160, 200

const one = require('onecolor');
var color = one([ 'LAB', 60, -28, -32 ]);
console.log(color.css());

Output:

rgb(93,93,93)

The calculated RGB value of 93, 93, 93 results in different colour (visually) and
also doesn't match the expected RGB value of 0, 160, 200.

Single letter shorthands to one-color-all?

It would help somewhat to have one letter shorthands for color properties at one-color-all. I'm thinking something along following aliases:

  • r -> red
  • g -> green
  • b -> blue
  • a -> alpha
  • h -> hue
  • s -> saturation
  • v -> value
  • l -> lightness
  • c -> cyan
  • m -> magenta
  • y -> yellow
  • k -> black

Publish 2.3.2 to the jam repo

@Munter I published 2.3.2, but I don't have credentials to publish to the jam repo, so the postpublish hook fails. Could you publish it or share your credentials with me? :)

PhantomJS Support

PhantomJS exposes a module object to its scripts. one-color-all-debug.js interprets the existence of this object as evidence that it's running in Node.js, and therefore doesn't need to add the one object to the window object. The result: scripts running in Phantom.js can't find the one object, and can't use the library.

To fix this, I'd suggest checking for the existence of window and adding the object to window, even if the module object exists.

library fails to load

if I include one-color.js or one-color-debug.js in a page in a script tag it fails saying that one is not defined

that is line 213 of the -debug file, the problem is that the variable "one" is not declared at the begining, adding the declaration fixes the problem.

if this breaks with the build process (that is, it's not exported) then maybe getting the global object (window) and assigning it there or checking if it's undefined and then initializing it will fix it too.

new Function() error in atom

At Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self'".

EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self'".

AMD Support

Could you please consider adding AMD support to the build? Check out UMD to figure out how to do it neatly. You can support browser globals, CommonJS and AMD in the same time even.

This would make it easier to integrate the library to colorjoe as this would allow the users to load this library and colorjoe as separate AMD module to their project.

Alternative constructor for CMYK?

It would be useful if it was possible to instantiate a CMYK color using one.color(["CMYK", .5, .1, .6, .9]) kind syntax. Relying on just "new" is a bit difficult due to the constructor. Alternatively you could try to change the new syntax to something like new one.color.CMYK([c, m, y, k, a]). That would work too.

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.