@ctrl/tinycolor

repository·master·Indexed 20 days ago

https://github.com/scttcper/tinycolor

A fast, small, and tree-shakeable JavaScript library for color manipulation and conversion. It provides a robust API for parsing, transforming, and inspecting colors in formats including Hex, RGB, HSL, and CMYK. Features include color harmony generation (analogous, monochromatic, triad), brightness and luminance calculation, alpha management, and a permissive constructor for string and object inputs.

Tokens
9.1K
Snippets
45
Records
51
Agent score
69%

What's inside @ctrl/tinycolor

  1. Differences between tinycolor and tinycolor2

    master

    If you are migrating from tinycolor2, note the following breaking changes:

    • The library is now written in TypeScript/ES2015 and requires Node >= 8.
    • It is tree-shakeable.
    • tinycolor is now exported as a class named TinyColor.
    • The default export has been removed; use import { TinyColor } from '@ctrl/tinycolor'.
    • readability and fromRatio have moved out of the TinyColor class.
    • random has been renamed to legacyRandom and moved out of the class.
    • toFilter has been renamed to toMsFilter and moved out of the class.
    • mix and equals now use the current TinyColor object as the first parameter.
    • isValid and format are now properties instead of functions.
  2. How luminosity affects color generation

    master

    The luminosity option adjusts both saturation and brightness to achieve specific visual effects:

    • 'random': Saturation and brightness are picked randomly within valid ranges.
    • 'bright': Increases the minimum saturation to ensure colors appear more vivid.
    • 'dark': Constrains brightness to a lower range.
    • 'light': Constrains brightness to a higher range.
    • 'monochrome': When used with hue: 'monochrome', saturation is forced to 0.
  3. Use seeds for repeatable random colors

    master

    By providing a seed (a number) in the RandomOptions, you can ensure that the random() function produces the same sequence of colors. This is useful for consistent UI generation or testing. When generating multiple colors via the count option, the function automatically increments the seed for each subsequent color in the array to prevent duplicates.

    // These two calls will produce the same color
    const color1 = random({ seed: 42 });
    const color2 = random({ seed: 42 });
  4. Basic usage of TinyColor

    master

    Import the TinyColor class from @ctrl/tinycolor and instantiate it with a color string or object. You can then call methods like toHexString() to get the color in a specific format.

    import { TinyColor } from '@ctrl/tinycolor';
    const color = new TinyColor('red').toHexString(); // '#ff0000'
  5. Generate random colors with random()

    master

    The random function returns a random TinyColor object. It is an implementation of randomColor by David Merfield, with input parsing and output formatting handled by TinyColor.

    Options

    You can pass an options object to influence the generated color:

    • hue: Controls the hue. Supported strings: red, orange, yellow, green, blue, purple, pink, and monochrome. You can also pass a hex string (e.g., #00FFFF) to extract its hue.
    • luminosity: Controls luminosity. Supported strings: bright, light, dark, or random.
    • count: An integer specifying the number of colors to generate (returns an array).
    • seed: An integer to ensure the same color is returned each time.
    • alpha: A decimal between 0 and 1. Only relevant for rgba and hsla formats. Defaults to a random value.
    import { random } from '@ctrl/tinycolor';
    // Returns a TinyColor for an attractive color
    random();
    
    // Returns an array of ten green colors
    random({
      count: 10,
      hue: 'green',
    });
    
    // Returns a TinyColor object in a light blue
    random({
      luminosity: 'light',
      hue: 'blue',
    });
    
    // Returns a TinyColor object in a 'truly random' color
    random({
      luminosity: 'random',
      hue: 'random',
    });
    
    // Returns a dark RGB color with specified alpha
    random({
      luminosity: 'dark',
      alpha: 0.5,
    });
  6. Convert colors to various string formats

    master

    TinyColor provides several methods to export colors as strings or objects:

    String Formats

    • toHexString(): Returns hex string with # (e.g., #ff0000).
    • toHex(): Returns hex string without # (e.g., ff0000).
    • toHex8String(): Returns 8-digit hex string with # (e.g., #ff0000ff).
    • toHex8(): Returns 8-digit hex string without # (e.g., ff0000ff).
    • toHexShortString(boolean): Returns a short hex string. If the boolean argument is true, it attempts to shorten it (e.g., #f00).
    • toRgbString(): Returns rgb() or rgba() string.
    • toHslString(): Returns hsl() or hsla() string.
    • toHsvString(): Returns hsv() or hsva() string.
    • toCmykString(): Returns cmyk() string.
    • toPercentageRgbString(): Returns rgb() string with percentage values.
    • toName(): Returns the CSS color name (e.g., red).
    • toString(format): A generic method to print to a string. You can pass formats like "rgb", "hex6", "hex3", "hex8", "name", "hsl", or "hsv" as an argument.
    const color = new TinyColor('red');
    color.toHexString(); // "#ff0000"
    color.toRgbString(); // "rgb(255, 0, 0)"
    color.toString('hsv'); // "hsv(0, 100%, 100%)"
  7. Get brightness and luminance of a color

    master

    Use getBrightness() to get the perceived brightness of a color on a scale of 0-255 (based on WCAG 1.0). Use getLuminance() to get the perceived luminance on a scale of 0-1 (based on WCAG 2.0).

    You can also use isLight() and isDark() to get a boolean indicating if the color's perceived brightness is light or dark.

    const color1 = new TinyColor('#fff');
    color1.getBrightness(); // 255
    color1.getLuminance(); // 1
    color1.isLight(); // true
    
    const color2 = new TinyColor('#000');
    color2.getBrightness(); // 0
    color2.getLuminance(); // 0
    color2.isDark(); // true
  8. Clone a TinyColor object with clone()

    master

    The clone method creates a new TinyColor instance with the same color values. This allows you to modify the new instance without affecting the original object.

    const color1 = new TinyColor('#F00');
    const color2 = color1.clone();
    color2.setAlpha(0.5);
    
    color1.toString(); // "#ff0000"
    color2.toString(); // "rgba(255, 0, 0, 0.5)"
  9. Manage color alpha (transparency)

    master

    Use getAlpha() to retrieve the alpha value from 0-1. Use setAlpha(value) to set a new alpha value between 0-1. This method modifies the current color instance and returns it for chaining.

    const color = new TinyColor('red');
    color.getAlpha(); // 1
    color.setAlpha(0.5);
    color.getAlpha(); // 0.5
    color.toRgbString(); // "rgba(255, 0, 0, 0.5)"
  10. Convert colors to objects or numbers

    master

    To Objects

    • toRgb(): Returns { r, g, b, a } where components are 0-255.
    • toHsv(): Returns { h, s, v, a }.
    • toHsl(): Returns { h, s, l, a }.
    • toPercentageRgb(): Returns { r, g, b, a } where components are strings like "100%".

    To Numbers

    • toNumber(): Returns the color as a single integer representation.
    const color = new TinyColor('red');
    color.toRgb(); // { r: 255, g: 0, b: 0, a: 1 }
    color.toHsv(); // { h: 0, s: 1, v: 1, a: 1 }
    
    new TinyColor('#aabbcc').toNumber(); // 0xaabbcc
  11. Compute color appearance on a background

    master

    The onBackground(backgroundColor) method computes how a color would appear when placed on a specific background.

    • If the color is fully transparent (getAlpha() == 0), the result is the background color.
    • If the color is fully opaque (getAlpha() == 1), the result is the color itself.
    • Otherwise, it returns a computed result representing the blended color.
    const color = new TinyColor('rgba(255, 0, 0, .5)');
    const computedColor = color.onBackground('rgb(0, 0, 255)');
    computedColor.toRgbString(); // "rgb(128, 0, 128)"