JavaScript Color Parsing - TinyColor

I threw together a color parsing library to help make my JavaScript colorpicker as small and accurate as possible. It is called TinyColor. One of the main goals is a small footprint - it clocks in at 8.98KB (3.41KB gzipped).

I have written in more detail about this on my TinyColor page. In it, I talk about the Color conversion, input recognition, color manipulation, scheme (combination) generation, and more.

Comments

  1. 0i0 (lior hakim) Says:

    very nice!

    check oute this patteren to scrap a few more bytes for places like line 185
    from

    switch(max) {
                case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                case g: h = (b - r) / d + 2; break;
                case b: h = (r - g) / d + 4; break;
            }

    to

    h = max == r ? (g - b) / d + (g < b ? 6 : 0):
        max == g ? (b - r) / d + 2:
        max == b ? (r - g) / d + 4:
        h;

    better looking and less code

  2. Brian Says:

    Yes, many of the conversion functions were modified from other sources, so I didn’t make many changes besides changing the bounding of the parameters (normalizing the input to a 0-1 scale).

    I usually avoid nested ternary expressions because it is hard to visually parse them out (at least when reading the code months later) so I end up explicitly parenthesizing the nesting, which makes it a little more verbose.

  3. János Takács Says:

    I think I’ve found some errors in your library. I tried to change the opacity of a color, but it did not gave the expected result. One of the problems is that the toRgbString function uses the variable named “a” instead of “this.alpha”. An other problem is, that the tinycolor function does not always gives back a tinycolor object, so sometimes some of the methods are not available.

    var color1=tinycolor("rgb(87,93,16)");
    color1.alpha=0.9;
    console.log(color1);
    console.log("color 1= "+color1.toRgbString()); // color 1= rgb(87, 93, 16)
     
    var c=color1.toRgb();
    console.log(c);
     
    var color2=tinycolor({
      r:c.r,
      g:c.g,
      b:c.b,
      a:0.9
    });
    console.log(color2);
    console.log("color 2= "+color2.toRgbString());  // color 2= rgba(87, 93, 16, 0.9)
     
    var color3=tinycolor({
      r:color1.r,
      g:color1.g,
      b:color1.b,
      a:0.9
    });
    console.log(color3);   // rgba( NaN, NaN, NaN, 0.9, ...)
    console.log(c.toRgbString()); // TypeError: c.toRgbString is not a function
  4. Brian Says:

    To change the alpha values, try color1.setAlpha(). For the other issue, can you open an issue here: https://github.com/bgrins/TinyColor/issues/new with the steps to reproduce?

Comments are closed. Please contact me instead.