Giter VIP home page Giter VIP logo

tinycolor's Introduction

TinyColor

JavaScript color tooling

TinyColor is a small, fast library for color manipulation and conversion in JavaScript. It allows many forms of input, while providing color conversions and other color utility functions. It has no dependencies.

Including in node

tinycolor can be installed from npm:

npm install tinycolor2

Then it can be used in your script like so:

var tinycolor = require("tinycolor2");
var color = tinycolor("red");

Or in a module like so:

import tinycolor from "tinycolor2";
var color = tinycolor("red");

Including in a browser

The package can be bundled from npm, but if you prefer to download it locally you have two choices:

ESM

It can be used as a module by downloading npm/esm/tinycolor.js or using https://esm.sh/tinycolor2.

<script type='module'>
import tinycolor from "https://esm.sh/tinycolor2";
var color = tinycolor("red");
</script>

UMD

You can use it directly in a script tag by downloading the UMD file from npm/cjs/tinycolor.js:

<script type='text/javascript' src='tinycolor.js'></script>
<script type='text/javascript'>
var color = tinycolor("red");
</script>

Usage

Call tinycolor(input) or new tinycolor(input), and you will have an object with the following properties. See Accepted String Input and Accepted Object Input below for more information about what is accepted.

Accepted String Input

The string parsing is very permissive. It is meant to make typing a color as input as easy as possible. All commas, percentages, parenthesis are optional, and most input allow either 0-1, 0%-100%, or 0-n (where n is either 100, 255, or 360 depending on the value).

HSL and HSV both require either 0%-100% or 0-1 for the S/L/V properties. The H (hue) can have values between 0%-100% or 0-360.

RGB input requires either 0-255 or 0%-100%.

If you call tinycolor.fromRatio, RGB and Hue input can also accept 0-1.

Here are some examples of string input:

Hex, 8-digit (RGBA) Hex

tinycolor("#000");
tinycolor("000");
tinycolor("#369C");
tinycolor("369C");
tinycolor("#f0f0f6");
tinycolor("f0f0f6");
tinycolor("#f0f0f688");
tinycolor("f0f0f688");

RGB, RGBA

tinycolor("rgb (255, 0, 0)");
tinycolor("rgb 255 0 0");
tinycolor("rgba (255, 0, 0, .5)");
tinycolor({ r: 255, g: 0, b: 0 });
tinycolor.fromRatio({ r: 1, g: 0, b: 0 });
tinycolor.fromRatio({ r: .5, g: .5, b: .5 });

HSL, HSLA

tinycolor("hsl(0, 100%, 50%)");
tinycolor("hsla(0, 100%, 50%, .5)");
tinycolor("hsl(0, 100%, 50%)");
tinycolor("hsl 0 1.0 0.5");
tinycolor({ h: 0, s: 1, l: .5 });
tinycolor.fromRatio({ h: 1, s: 0, l: 0 });
tinycolor.fromRatio({ h: .5, s: .5, l: .5 });

HSV, HSVA

tinycolor("hsv(0, 100%, 100%)");
tinycolor("hsva(0, 100%, 100%, .5)");
tinycolor("hsv (0 100% 100%)");
tinycolor("hsv 0 1 1");
tinycolor({ h: 0, s: 100, v: 100 });
tinycolor.fromRatio({ h: 1, s: 0, v: 0 });
tinycolor.fromRatio({ h: .5, s: .5, v: .5 });

Named

Case insenstive names are accepted, using the list of colors in the CSS spec.

tinycolor("RED");
tinycolor("blanchedalmond");
tinycolor("darkblue");

Accepted Object Input

If you are calling this from code, you may want to use object input. Here are some examples of the different types of accepted object inputs:

{ r: 255, g: 0, b: 0 }
{ r: 255, g: 0, b: 0, a: .5 }
{ h: 0, s: 100, l: 50 }
{ h: 0, s: 100, v: 100 }

Methods

getFormat

Returns the format used to create the tinycolor instance

var color = tinycolor("red");
color.getFormat(); // "name"
color = tinycolor({r:255, g:255, b:255});
color.getFormat(); // "rgb"

getOriginalInput

Returns the input passed into the constructor used to create the tinycolor instance

var color = tinycolor("red");
color.getOriginalInput(); // "red"
color = tinycolor({r:255, g:255, b:255});
color.getOriginalInput(); // "{r: 255, g: 255, b: 255}"

isValid

Return a boolean indicating whether the color was successfully parsed. Note: if the color is not valid then it will act like black when being used with other methods.

var color1 = tinycolor("red");
color1.isValid(); // true
color1.toHexString(); // "#ff0000"

var color2 = tinycolor("not a color");
color2.isValid(); // false
color2.toString(); // "#000000"

getBrightness

Returns the perceived brightness of a color, from 0-255, as defined by Web Content Accessibility Guidelines (Version 1.0).

var color1 = tinycolor("#fff");
color1.getBrightness(); // 255

var color2 = tinycolor("#000");
color2.getBrightness(); // 0

isLight

Return a boolean indicating whether the color's perceived brightness is light.

var color1 = tinycolor("#fff");
color1.isLight(); // true

var color2 = tinycolor("#000");
color2.isLight(); // false

isDark

Return a boolean indicating whether the color's perceived brightness is dark.

var color1 = tinycolor("#fff");
color1.isDark(); // false

var color2 = tinycolor("#000");
color2.isDark(); // true

getLuminance

Returns the perceived luminance of a color, from 0-1 as defined by Web Content Accessibility Guidelines (Version 2.0).

var color1 = tinycolor("#fff");
color1.getLuminance(); // 1

var color2 = tinycolor("#000");
color2.getLuminance(); // 0

getAlpha

Returns the alpha value of a color, from 0-1.

var color1 = tinycolor("rgba(255, 0, 0, .5)");
color1.getAlpha(); // 0.5

var color2 = tinycolor("rgb(255, 0, 0)");
color2.getAlpha(); // 1

var color3 = tinycolor("transparent");
color3.getAlpha(); // 0

setAlpha

Sets the alpha value on a current color. Accepted range is in between 0-1.

var color = tinycolor("red");
color.getAlpha(); // 1
color.setAlpha(.5);
color.getAlpha(); // .5
color.toRgbString(); // "rgba(255, 0, 0, .5)"

String Representations

The following methods will return a property for the alpha value, which can be ignored: toHsv, toHsl, toRgb

toHsv

var color = tinycolor("red");
color.toHsv(); // { h: 0, s: 1, v: 1, a: 1 }

toHsvString

var color = tinycolor("red");
color.toHsvString(); // "hsv(0, 100%, 100%)"
color.setAlpha(0.5);
color.toHsvString(); // "hsva(0, 100%, 100%, 0.5)"

toHsl

var color = tinycolor("red");
color.toHsl(); // { h: 0, s: 1, l: 0.5, a: 1 }

toHslString

var color = tinycolor("red");
color.toHslString(); // "hsl(0, 100%, 50%)"
color.setAlpha(0.5);
color.toHslString(); // "hsla(0, 100%, 50%, 0.5)"

toHex

var color = tinycolor("red");
color.toHex(); // "ff0000"

toHexString

var color = tinycolor("red");
color.toHexString(); // "#ff0000"

toHex8

var color = tinycolor("red");
color.toHex8(); // "ff0000ff"

toHex8String

var color = tinycolor("red");
color.toHex8String(); // "#ff0000ff"

toRgb

var color = tinycolor("red");
color.toRgb(); // { r: 255, g: 0, b: 0, a: 1 }

toRgbString

var color = tinycolor("red");
color.toRgbString(); // "rgb(255, 0, 0)"
color.setAlpha(0.5);
color.toRgbString(); // "rgba(255, 0, 0, 0.5)"

toPercentageRgb

var color = tinycolor("red");
color.toPercentageRgb() // { r: "100%", g: "0%", b: "0%", a: 1 }

toPercentageRgbString

var color = tinycolor("red");
color.toPercentageRgbString(); // "rgb(100%, 0%, 0%)"
color.setAlpha(0.5);
color.toPercentageRgbString(); // "rgba(100%, 0%, 0%, 0.5)"

toName

var color = tinycolor("red");
color.toName(); // "red"

toFilter

var color = tinycolor("red");
color.toFilter(); // "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffff0000,endColorstr=#ffff0000)"

toString

Print to a string, depending on the input format. You can also override this by passing one of "rgb", "prgb", "hex6", "hex3", "hex8", "name", "hsl", "hsv" into the function.

var color1 = tinycolor("red");
color1.toString(); // "red"
color1.toString("hsv"); // "hsv(0, 100%, 100%)"

var color2 = tinycolor("rgb(255, 0, 0)");
color2.toString(); // "rgb(255, 0, 0)"
color2.setAlpha(.5);
color2.toString(); // "rgba(255, 0, 0, 0.5)"

Color Modification

These methods manipulate the current color, and return it for chaining. For instance:

tinycolor("red").lighten().desaturate().toHexString() // "#f53d3d"

lighten

lighten: function(amount = 10) -> TinyColor. Lighten the color a given amount, from 0 to 100. Providing 100 will always return white.

tinycolor("#f00").lighten().toString(); // "#ff3333"
tinycolor("#f00").lighten(100).toString(); // "#ffffff"

brighten

brighten: function(amount = 10) -> TinyColor. Brighten the color a given amount, from 0 to 100.

tinycolor("#f00").brighten().toString(); // "#ff1919"

darken

darken: function(amount = 10) -> TinyColor. Darken the color a given amount, from 0 to 100. Providing 100 will always return black.

tinycolor("#f00").darken().toString(); // "#cc0000"
tinycolor("#f00").darken(100).toString(); // "#000000"

desaturate

desaturate: function(amount = 10) -> TinyColor. Desaturate the color a given amount, from 0 to 100. Providing 100 will is the same as calling greyscale.

tinycolor("#f00").desaturate().toString(); // "#f20d0d"
tinycolor("#f00").desaturate(100).toString(); // "#808080"

saturate

saturate: function(amount = 10) -> TinyColor. Saturate the color a given amount, from 0 to 100.

tinycolor("hsl(0, 10%, 50%)").saturate().toString(); // "hsl(0, 20%, 50%)"

greyscale

greyscale: function() -> TinyColor. Completely desaturates a color into greyscale. Same as calling desaturate(100).

tinycolor("#f00").greyscale().toString(); // "#808080"

spin

spin: function(amount = 0) -> TinyColor. Spin the hue a given amount, from -360 to 360. Calling with 0, 360, or -360 will do nothing (since it sets the hue back to what it was before).

tinycolor("#f00").spin(180).toString(); // "#00ffff"
tinycolor("#f00").spin(-90).toString(); // "#7f00ff"
tinycolor("#f00").spin(90).toString(); // "#80ff00"

// spin(0) and spin(360) do nothing
tinycolor("#f00").spin(0).toString(); // "#ff0000"
tinycolor("#f00").spin(360).toString(); // "#ff0000"

Color Combinations

Combination functions return an array of TinyColor objects unless otherwise noted.

analogous

analogous: function(, results = 6, slices = 30) -> array<TinyColor>.

var colors = tinycolor("#f00").analogous();

colors.map(function(t) { return t.toHexString(); }); // [ "#ff0000", "#ff0066", "#ff0033", "#ff0000", "#ff3300", "#ff6600" ]

monochromatic

monochromatic: function(, results = 6) -> array<TinyColor>.

var colors = tinycolor("#f00").monochromatic();

colors.map(function(t) { return t.toHexString(); }); // [ "#ff0000", "#2a0000", "#550000", "#800000", "#aa0000", "#d40000" ]

splitcomplement

splitcomplement: function() -> array<TinyColor>.

var colors = tinycolor("#f00").splitcomplement();

colors.map(function(t) { return t.toHexString(); }); // [ "#ff0000", "#ccff00", "#0066ff" ]

triad

triad: function() -> array<TinyColor>.

var colors = tinycolor("#f00").triad();

colors.map(function(t) { return t.toHexString(); }); // [ "#ff0000", "#00ff00", "#0000ff" ]

tetrad

tetrad: function() -> array<TinyColor>.

var colors = tinycolor("#f00").tetrad();

colors.map(function(t) { return t.toHexString(); }); // [ "#ff0000", "#80ff00", "#00ffff", "#7f00ff" ]

complement

complement: function() -> TinyColor.

tinycolor("#f00").complement().toHexString(); // "#00ffff"

Color Utilities

tinycolor.equals(color1, color2)
tinycolor.mix(color1, color2, amount = 50)

random

Returns a random color.

var color = tinycolor.random();
color.toRgb(); // "{r: 145, g: 40, b: 198, a: 1}"

Readability

TinyColor assesses readability based on the Web Content Accessibility Guidelines (Version 2.0).

readability

readability: function(TinyColor, TinyColor) -> Object. Returns the contrast ratio between two colors.

tinycolor.readability("#000", "#000"); // 1
tinycolor.readability("#000", "#111"); // 1.1121078324840545
tinycolor.readability("#000", "#fff"); // 21

Use the values in your own calculations, or use one of the convenience functions below.

isReadable

isReadable: function(TinyColor, TinyColor, Object) -> Boolean. Ensure that foreground and background color combinations meet WCAG guidelines. Object is optional, defaulting to {level: "AA",size: "small"}. level can be "AA" or "AAA" and size can be "small" or "large".

Here are links to read more about the AA and AAA requirements.

tinycolor.isReadable("#000", "#111", {}); // false
tinycolor.isReadable("#ff0088", "#5c1a72",{level:"AA",size:"small"}); //false
tinycolor.isReadable("#ff0088", "#5c1a72",{level:"AA",size:"large"}), //true

mostReadable

mostReadable: function(TinyColor, [TinyColor, Tinycolor ...], Object) -> Boolean. Given a base color and a list of possible foreground or background colors for that base, returns the most readable color. If none of the colors in the list is readable, mostReadable will return the better of black or white if includeFallbackColors:true.

tinycolor.mostReadable("#000", ["#f00", "#0f0", "#00f"]).toHexString(); // "#00ff00"
tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255"
tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString();  // "#ffffff"
tinycolor.mostReadable("#ff0088", ["#2e0c3a"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString()   // "#2e0c3a",
tinycolor.mostReadable("#ff0088", ["#2e0c3a"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString()   // "#000000",

See index.html in the project for a demo.

Common operations

clone

clone: function() -> TinyColor. Instantiate a new TinyColor object with the same color. Any changes to the new one won't affect the old one.

var color1 = tinycolor("#F00");
var color2 = color1.clone();
color2.setAlpha(.5);

color1.toString(); // "#ff0000"
color2.toString(); // "rgba(255, 0, 0, 0.5)"

tinycolor's People

Contributors

0xflotus avatar akhoury avatar alephmelo avatar andersondo avatar antoinepairet avatar bfontaine avatar bgrins avatar cpsubrian avatar denniskehrig avatar ianb avatar jonathan-eyler-werve avatar jt3k avatar l2jliga avatar lboynton avatar levithomason avatar m-zuber avatar marcandre avatar markgriffiths avatar mrkeyboard avatar neogeek avatar owiber avatar ozan avatar phlipper avatar raspo avatar robianmcd avatar sebmck avatar stu-blair avatar tylersticka avatar vincentcr avatar z38 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  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

tinycolor's Issues

toHex / toHexString fails in IE7 or quirks mode

I figured out why. You're using a non-standard way to get a character from a string.

Array-like character access (the second way above) is not part of ECMAScript 3. It is a JavaScript and ECMAScript 5 feature.

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String#Character_access

// Return a 3 character hex if possible
    if (hex[0][0] == hex[0][1] && hex[1][0] == hex[1][1] && hex[2][0] == hex[2][1]) {
        return hex[0][0] + hex[1][0] + hex[2][0];
    }

should be

// Return a 3 character hex if possible
    if (hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
        return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
    }

Thanks for the plugin, it's pretty awesome.

Dialog on contributing and future plans

Hi there goodfellow Grinstead :). Super stoked to see your lib. I have tested a few others and was leaning toward writing my own, until I found TinyColor. You have saved me tons of time, so thanks!

My goal is to have a lib that provides feature rich color manipulation, color scheme generation and manipulation, and some nice utilities. It looks like you are largely doing this and I'd like to help. I am also curious as to your future plans for TinyColor, what you'd like it to do and not do, your plans for contributors, etc.

I need your library. I am building a Bootstrap customizer called Bootstyle www.usebootstyle.com (project page). Bootstyle aims to be a robust designer tool for developers.

As mentioned, I have been trying to crack the color manipulation and scheme generation nut. These are the libs I've previously reviewed, used, and/or wrapped:

  • less.js
    • started wrapping their color functions as an angularjs service, abandoned this effort in hopes of finding a great lib
  • color
    • lots of features
    • doesn't do scheme generation
  • color-js
    • chose to run with color over color-js mostly due to syntax preferences
    • both do great color manipulation and no scheme generation
  • color-scheme-js
    • filled the scheme generation gap with this
    • really great lib with a great demo
    • there were some things that seemed odd to me regarding scheme generation (i.e. ignoring lightness/saturation, and generating hard coded tints and shades, no control for number of results or slices, etc.)
    • it also has many really awesome features like scheme variations (pastel, hard, etc.) and distance for generated colors (degree offset)
  • jQuery-xcolor
    • this one really got me excited. It looked like it had everything I needed and some cool bonuses, like animating color changes.
    • no distance again for generated schemes

My hope after all this is to plant myself with TinyColor. I really felt at home with the philosophy I see in how TinyColor works. In order to do this, there are a few features I'd love to get merged. I have started a couple just to kick things off but feel I need to discuss larger plans with you before really diving in. In the meantime, I have submitted a PR for brightness methods and am mostly done knocking out #18 spin.

I have lots more I'd like to discuss and hear from you on. What is the best way for us to do that?

Thanks again, really looking forward to your response.

Make HSV output format match input format

Lines from the README:

t.toHsv() // {"h":0,"s":1,"v":1}

tinycolor({ h: 0, s: 100, v: 100 });

In the first case, s and v have a range [0,1], while in the second they have a range of [0-100]. This makes converting back and forth between HSV a pain in the butt.

add brightness function

ok, this is quite tricky, at first I thought you had a bug in your lighten function but it appears to be just right to the "standard": http://en.wikipedia.org/wiki/HSL_and_HSV#Lightness
but what I was really looking for was brighten function (according to the wikipedia page).
given the hex code of black #000000 brighten by 50% should be #7f7f7f (while lighten gives back #808080)
here, this tool: hexcolortool.com uses lighten like this.
the brighten function is the "standard" lighten function in many places, for example in sass (which is why I was confused) and many, many standard libraries (e.g, even the Java library: http://www.java2s.com/Code/Java/2D-Graphics-GUI/Lightensacolorbyagivenamount.htm )

brighten function is really necessary, and should be explained to differentiate from the current lighten IMO. thanks.

Add tags to make Bower happy

Bower uses semver-compatible git tags to determine what version users should download.

To register a new package, there must be a valid manifest JSON in the current working directory, your package must be available at a Git endpoint (e.g., GitHub), and it should use semver Git tags.

In the absence of tags, it uses 'head'. It is generally better to have tags. :octocat:

Publish 0.9.16 to npm?

The latest package.json indicates the version's at 0.9.16, but the one on npm is at 0.9.9.

Feature request: setHue, setSaturation and setBrightness methods

Hi first of all thanks for this amazing library. I'm using it for the next release of bootstrap-colorpicker and I am trying to guess how to implement or emulate these methods correctly. It would be interesting to have them.

What I do now is convert the original tinycolor object with toHsv(), and create a new one compounding and passing an object like {h:360,v:100,s:100,a:1}. I don't know if this is the proper way or there is any better solution. May I loss color information?

The current integration with colorpicker is buggy yet, but If you download the tinycolor branch you can see it in action.

Thank you again

Copy or clone color

I would like to copy or clone a color so any changes will not mess the source.

chaining manipulation methods

would be very useful to do something like this:

tinycolor.lighten('#FF0000', 20).desaturate(20); // and so on

so the color manipulation functions should check the this, and if it's a tinycolor object, then work with it. make all methods a prototype of the object instance, so they will be available. now they are not..

Negative Value for HUE

I find your library useful thanks you. But for my purposes there is a one little bug with negative hue value, please fix them it's line 784:
var m1 = Number(match[1]);
return { h: ( m1 > 0 ? (m1 > 360 ? m1 - 360 : m1 ) : 360 + m1 ), s: match[2], l: match[3] };

Best Regards,
Vladimir Minkin

WCAG version 2.0

This is an excellent library! Thank you.

Reading the annotated source code, I see that the readability routines refer to http://www.w3.org/TR/AERT#color-contrast, which in turn is based on the Web Content Accessibility Guidelines Version 1.0.

I have previously incorporated the slightly different WCAG Version 2.0 algorithm (http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef) in a VBA project, and will probably update my downloaded copy of this library to use it. I am unfamiliar with working in the Open Source world, but if someone could give me a brief description of what I would need to do to port that work back (assuming anyone is interested!) I would be happy to contribute.

Better alpha support?

I very much love this little package, however for my purposes I need to modify a lot of alpha values for canvas rendering. While the tinycolor object has an alpha variable, it's not used really in the code, and I can't figure out any way to modify an existing color's alpha without casting into an RGB object, setting .a, and sending back into a tinycolor, or modifying the to*String results. Am I missing something?

Missing documentation

Disclaimer: I understand that not all of these are necessarily supposed to be documented

The following properties of the static tinyclor object are missing from the documentation:

  • hexNames
  • name
  • names
  • length
  • random
  • mix (it is present but not explained)

The following methods are missing from the instance object:

  • getFormat
  • getOriginalInput

Make hex6 the default for toHexString() and toHex()

This is one of the most confusing / problematic parts of the plugin. People are expecting / looking for 6 char hexes. Allow an override to allow it to be coerced to 3 characters instead of assuming this as the default.

Uniform full length hex input like #ffffff is not preserved on output from .toHexString()

If you create a new tinycolor('#ffffff'), the result of .toHexString() is '#fff' and does not match the input. See this fiddle for an example: http://jsfiddle.net/2va59/3/

This causes problems if you happened to be keying an object by hex value, for example, and depend on the output of TinyColor (via the Spectrum color picker, btw) to look up the correct values.

{"#e55731":{"field":"9","detail":"386"},"#ffffff":{"field":"15","detail":"387"})

The simple solution is to disable this if() statement entirely, but I could see an argument for an alternative .toFullHexString() method or an passing an optional argument (in pseudo-code) along the lines of .toHexString(bool shortenHexIfPossible = false) as well.

cdnjs integration

Hy, I opened a pull-request to distribute your lovely library in cdnjs.com. Just wanted to let you know, so you could add personal information (e.g. your email), contributors, new updates.

Thanks again for sharing

spin

This is more of a feature request / offer

Using tinycolor to compliment a LESS/bootstrap variable configuration page I'm working on, I implemented the spin code that is found in LESS (and SASS as adjust-hue)

    tinycolor.spin = function(color,amount) {
        var hsl = tinycolor(color).toHsl();
        var hue = (hsl.h + amount) % 360;
        hsl.h = hue < 0 ? 360 + hue : hue;
        return tinycolor(hsl);
    }

hex8 and hex4 support and formatting

Excellent stuff, but times move on (!)...

The latest W3C draft on CSS colour has the alpha channel of hex8 defined by the last two characters. So "00" is transparent, "80" is 50%, "FF" is opaque, etc.

http://dev.w3.org/csswg/css-color-4/#hex-notation

tinyColor formats this the other way around, with the alpha channel as the first two characters. I think that was the previous assumption.

So that also means that if we can have tinyColor accepting hex6 as shorthand for hex6, then will it be able to accept hex4 as shorthand for hex8 at some point in the future.

If anyone has a code fix for doing this NOW, you will magically appear on my Christmas Card list.

Thanks.

.lighten() doesn't seem to work properly

I would like to start by saying that this script is awesome! Thank you very much!

I have implemented a lighten method on a hex color and noticed that after a certain amount, the color is white (#fff), though way before the lighten value makes it to 100. It seems to create white when you pass in an argument that is 50. The same holds true if you use the .darken() method. Is the lighten argument a % value as to how much to lighten the color? Please see below and let me know when you can. I'm using the meteor version of this if that helps.

It seems that a lot of colors other than black will turn to white (#fff) once the lighten argument hits 50.
tinycolor("#f00").lighten(50).toString(); // new hex value for red is white (#fff)

It seems that a lot of colors other than black will turn to black (#000) once the darken argument hits 50.
tinycolor("#f00").darken(50).toString(); // new hex value for red is black (#000)

Black on the other hand seems to take a lighten value all the way up to 100
tinycolor("#000").lighten(100).toString(); // Only when the value is 100 does this new value make it to white (#fff)

After testing a few other colors, it seems inconsistent behavior. See another example below:

00CC00 = green

tinycolor("#00CC00").lighten(60).toString(); // creates white (#fff)
tinycolor("#00CC00").darken(40).toString(); // creates black (#000)

Any help with this would be awesome. Thank you again! -Chris

Not sure if you are implementing something like this, though want to share:
http://stackoverflow.com/questions/5560248/programmatically-lighten-or-darken-a-hex-color-or-rgb-and-blend-colors

Reability returns contrast only for solid colours (WCAG)

Hi All,

The TC readability function returns the contrast ratios of two colours. But even is an alpha colour is passed in the param the ratio returned is only for solid colours.

So passing:

"rgba(0, 102, 161, 0.5)", "fff"

and

"rgb(0, 102, 161)", "fff"

yields the same ratio (6.15).

I come up against designers that use alpha an awful lot, and working out the effective contrast ratio to meet with WCAG is a real pain.

Can TC please be made to support alpha colours? A bit like this one:

https://github.com/LeaVerou/contrast-ratio

If anyone knows how to do this, you will be on my Christmas card list!

Cheers

Lighten will remove the hue and saturation when reaches 100%.

var a = tinycolor('hsl(11, 100%, 96%)')
console.log(a.toString()); // "hsl(11, 100%, 96%)"
a.lighten(10);
console.log(a.toString()); // "hsl(0, 0%, 100%)"

I would expect to be

console.log(a.toString()); // "hsl(11, 100%, 100%)"

In your docs you say "Providing 100 will always return white." but I think is a good idea to keep the data anyway, in this case I need to darken and instead of being red again, is grey.

IMO a.lighten(10) and then a.darken(10) should reverse to the initial color.

RGBA hex

The doc gives this example: tinycolor("#88f0f0f6"), but it doesn't work:

tinycolor("#88f0f0f6").toRgb() # => {a: 1, b: 0, g: 0, r:0}

toRgbString doc is missleading (misses alpha)

Is toRgbString but your doc seems to not support it

toRgbString
var color = tinycolor("red");
color.toRgbString(); // "rgb(255, 0, 0)"

please add another example

toRgbString
var color = tinycolor("red").setAlpha(0.5);
color.toRgbString(); // "rgba(255, 0, 0, 0.5)"

toFilter() references secondColor

In this code:

            if (secondColor) {
                var s = tinycolor(secondColor);
                secondHex = s.toHex();
                secondAlphaHex = Math.round(parseFloat(s.alpha) * 255).toString(16);
            }

I'm not sure what it's supposed to be referencing, but secondColor isn't defined there (opts.secondColor?)

rgb range 0-1 not correctly recognized

I would expect it to recognize a range of [0-1] if all numbers are decimal and bound to 0-1, as in older version (this result is from v0.5):

tinycolor('rgb(0.9, 0.0, 0.0)').toRgbString()
"rgb(230, 0, 0)"

But it now seems to only work when there's a 1.0 somewhere (at least after 0.9.14):

tinycolor('rgb(0.9, 0.0, 0.0)').toRgbString()
"rgb(1, 0, 0)"
tinycolor('rgb(1.0, 0.0, 0.0)').toRgbString()
"rgb(255, 0, 0)"

Am I doing it wrong? Should I try to fix it?

Potential toString vs getOriginalInput confusion

In having adobe/brackets#9596 reviewed, @redmunds brought out an interesting observation:

(Me) tinycolor.toString() actually works as the author intended. It does not ignore the original case, but rather normalizes (to lowercase) it before returning it. There was actually no way to get the original input (it wasn't even stored) until I suggested it and sent a patch in the form of tinycolor.getOriginalInput().

Yes, but since you added tinycolor.getOriginalInput(), I think it changes expectations. I would expect that method to be called something like toNormalizedString().

I am wondering what your thoughts are on this, @bgrins. I know toString() is a long-standing method and removing/renaming it would be a huge breaking change, but would it be possible to better document the normalization it performs and/or rename getOriginalInput() to something that better describes it's actions vs toString()? I mention renaming as it is a very recent edition to TinyColor and probably isn't used much yet.

Option to restrict hex to require '#' char (or as validation option)

This library is great, using it to validate and preview user-entered colors in a theming UI.

One issue I ran into:

  • we write the theming input values straight out into the css as strings.
  • TinyColor will parse 'fff' or 'ffffff' as valid colors (no '#' char). This is great for ease of use, but when written out as strings into css, the browser doesn't parse these as colors.

A possible solution for me would be to post-process these when the form is saved. I'd prefer to restrict the input to valid values though. I had a read of TinyColor js to see if I had missed any obvious options for this, but didn't spot any.

Is there an option I'm missing? Or would you consider providing these, either for TinyColour object init, or for the isValid() function. NP if this is a weird use case and the answer is no. Workarounds would be found :)

-- EDIT --
I wrote additional validation using the private _format property of TinyColor object. Using the private var might break in future, but it was a lightweight solution that works nicely.

        var color_is_valid = false;
        if (color.isValid() == true) {
            if (color._format == 'hex') {
                if (input_value.charAt(0) == '#') {
                    color_is_valid = true;
                }
            } else if (color._format == 'rgb' || color._format == 'rgba') {
                if (input_value.charAt(input_value.length-1) == ')') {
                    color_is_valid = true;
                }
            } else {
                color_is_valid = true;
            }
        }

Contrast Color

Hi, it's possible to add function getContrast to show contrast color like less :

Example

p  {
    a: contrast(#bbbbbb);
    b: contrast(#222222, #101010);
    c: contrast(#222222, #101010, #dddddd);
    d: contrast(hsl(90, 100%, 50%), #000000, #ffffff, 30%);
    e: contrast(hsl(90, 100%, 50%), #000000, #ffffff, 80%);
}

Output

p {
    a: #000000 // black
    b: #ffffff // white
    c: #dddddd
    d: #000000 // black
    e: #ffffff // white
}

Transformation functions don't allow intentional passing of 0 amount

The various transformation functions such as lighten, darken, saturate, and desaturate accept a second argument for the amount of change. If that argument is not provided, a default of 10% is used, e.g. for darken . The boolean test to see if that argument is present checks whether the amount argument is "falsy."

While a missing argument is falsy, so is 0, which I think should be a valid value to pass into this function. In particular, in iteration loops where gradients are being calculated over a collection of elements on a page, the color of the first item in the gradient will differ from the gradient start by 0, i.e. it will be identical to the gradient start. A natural way to code this might be (using underscore.js), something like:

var gradientStartColor = ....;
var darkeningAmount = ....;
var colors = _.map(_.range(numElements), function(elemNum) {
  return tinycolor.darken(gradientStartColor, elemNum * darkeningAmount);
});

However, on the first iteration, elemNum will be 0, which means that the second argument to darken will be (intentionally) 0. This doesn't result in darken being the expected no-op on that iteration, however, since the default of 10% will be selected instead by darken because 0 is falsy.

Can the argument checks / defaults in the transformation functions account for the case of passing 0? I think that's a pretty natural way to code iterative transformations without special casing.

Thanks.

Get first readable

I know that is possible to do this with the API already provided but would be nice to have this. For example I have a list of possible colors and I would like to get the first one that is readable above a certain threshold.

HSV is somehow miss documented

Your values for h in hsv is 0-360 in range.

h = bound01(h, 360) * 6;

In your main doc you say

All commas, percentages, parenthesis are optional, and most input allow either 0-1, 0%-100%, or 0-n (where n is either 100, 255, or 360 depending on the value).

But right below you say:

HSL and HSV both require either 0%-100% or 0-1.

It should be

HSL and HSV both require either 0%-100% or 0-1. H can have values between 0-1 or 0-360.

License?

What is the license for TinyColor?

darken() => undefined is not a function

If I for instance do this: tinycolor("#f00").darken() I get:

undefined is not a function

I have tried to iterate through tinycolor and it seems that it do have the function `darken``

Preserve input case

Could you add the ability to preserve the case of the input value when toString() is called? For (an highly simplistic and silly) example, if I run tinycolor("RGB(39, 39, 39)") though TinyColor then call toString() in it without converting it, I get rgb(39, 39, 39) in return. I'm trying to implement an uppercase-lowercase converter in a program I can't change much of that uses TinyColor, and the always-lowercase return is making it a bit difficult.

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.