Hello everyone, long time no see, my name is Rong Ding, because I often need to use color in JavaScript, and to deal with these effectively requires a certain understanding of color format and conversion. So I’ve compiled 13 code snippets for most of your everyday needs, from randomly generating hexadecimal colors, to converting between hexadecimal and RGB values, and even some more advanced tricks like changing the brightness of colors using HSL formats…

Good nonsense not to say ~ on the code!

Random hexadecimal color generation

// Randomly generate hexadecimal colors
const randomHexColorCode = () = > {
  let n = (Math.random() * 0xfffff * 1000000).toString(16);
  return "#" + n.slice(0.6);
};

/ / use
randomHexColorCode(); // '#e34155'
Copy the code

RGB to hexadecimal

//RGB to hexadecimal
const RGBToHex = (r, g, b) = >
  ((r << 16) + (g << 8) + b).toString(16).padStart(6."0");

/ / use
RGBToHex(255.165.1); // '#ffa501'
Copy the code

Convert hexadecimal to RGB

// Convert hexadecimal to RGB
const hexToRGB = (hex) = > {
  let alpha = false,
    h = hex.slice(hex.startsWith("#")?1 : 0);
  if (h.length === 3) h = [...h].map((x) = > x + x).join("");
  else if (h.length === 8) alpha = true;
  h = parseInt(h, 16);
  return (
    "rgb" +
    (alpha ? "a" : "") +
    "(" +
    (h >>> (alpha ? 24 : 16)) +
    "," +
    ((h & (alpha ? 0x00ff0000 : 0x00ff00)) >>> (alpha ? 16 : 8)) +
    "," +
    ((h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 8 : 0)) +
    (alpha ? `, ${h & 0x000000ff}` : "") +
    ")"
  );
};

/ / use
hexToRGB("#27ae60ff"); // 'rgba(39, 174, 96, 255)'
hexToRGB("27ae60"); // 'rgb(39, 174, 96)'
hexToRGB("#fff"); // 'rgb(255, 255, 255)'
Copy the code

Expand 3-bit color to 6-bit color

// Expand hexadecimal 3-bit colors to 6-bit colors
const extendHex = (shortHex) = >
  "#" +
  shortHex
    .slice(shortHex.startsWith("#")?1 : 0)
    .split("")
    .map((x) = > x + x)
    .join("");

/ / use
extendHex("#03f"); // '#0033ff'
extendHex("05a"); // '#0055aa'
Copy the code

Convert RGB () color strings to objects with values for each color.

// Convert RGB () color strings to objects with values for each color.
const toRGBObject = (rgbStr) = > {
  const [red, green, blue] = rgbStr.match(/\d+/g).map(Number);
  return { red, green, blue };
};

/ / use
toRGBObject("rgb(255, 12, 0)"); // {red: 255, green: 12, blue: 0}
Copy the code

Convert RGB () color strings to arrays

// Convert RGB () color strings to arrays
const toRGBArray = (rgbStr) = > rgbStr.match(/\d+/g).map(Number);

/ / use
toRGBArray("rgb(255, 12, 0)"); / / [12, 255, 0]
Copy the code

Convert RGB color tuples to HSB format.

// Convert RGB color tuples to HSB format.
const RGBToHSB = (r, g, b) = > {
  r /= 255;
  g /= 255;
  b /= 255;
  const v = Math.max(r, g, b),
    n = v - Math.min(r, g, b);
  const h =
    n === 0
      ? 0
      : n && v === r
      ? (g - b) / n
      : v === g
      ? 2 + (b - r) / n
      : 4 + (r - g) / n;
  return [60 * (h < 0 ? h + 6 : h), v && (n / v) * 100, v * 100];
};

/ / use
RGBToHSB(252.111.48);
/ / [18.529411764705856, 80.95238095238095, 98.82352941176471]
Copy the code

Convert HSB color tuples to RGB format.

// Convert the HSB color tuple to RGB format.
const HSBToRGB = (h, s, b) = > {
  s /= 100;
  b /= 100;
  const k = (n) = > (n + h / 60) % 6;
  const f = (n) = > b * (1 - s * Math.max(0.Math.min(k(n), 4 - k(n), 1)));
  return [255 * f(5), 255 * f(3), 255 * f(1)];
};

/ / use
HSBToRGB(18.81.99); / / [252.45, 109.31084999999996, 47.965499999999984]
Copy the code

Convert RGB color tuples to HSL format.

// Convert RGB color tuples to HSL format.
const RGBToHSL = (r, g, b) = > {
  r /= 255;
  g /= 255;
  b /= 255;
  const l = Math.max(r, g, b);
  const s = l - Math.min(r, g, b);
  const h = s
    ? l === r
      ? (g - b) / s
      : l === g
      ? 2 + (b - r) / s
      : 4 + (r - g) / s
    : 0;
  return [
    60 * h < 0 ? 60 * h + 360 : 60 * h,
    100 * (s ? (l <= 0.5 ? s / (2 * l - s) : s / (2 - (2 * l - s))) : 0),
    (100 * (2 * l - s)) / 2,]; };/ / use
RGBToHSL(45.23.11); / / [21.17647, 60.71428, 10.98039]
Copy the code

Convert HSL color tuples to RGB format.

// Convert the HSL color tuple to RGB format.
const HSLToRGB = (h, s, l) = > {
  s /= 100;
  l /= 100;
  const k = (n) = > (n + h / 30) % 12;
  const a = s * Math.min(l, 1 - l);
  const f = (n) = >
    l - a * Math.max(-1.Math.min(k(n) - 3.Math.min(9 - k(n), 1)));
  return [255 * f(0), 255 * f(8), 255 * f(4)];
};

/ / use
HSLToRGB(13.100.11); / / [56.1, 12.155, 0]
Copy the code

Changes the brightness value of the HSL () color string.

// Change the brightness value of the HSL () color string.
const changeLightness = (delta, hslStr) = > {
  const [hue, saturation, lightness] = hslStr.match(/\d+/g).map(Number);
  const newLightness = Math.max(
    0.Math.min(100, lightness + parseFloat(delta))
  );
  return `hsl(${hue}.${saturation}%, ${newLightness}%) `;
};

/ / use
changeLightness(10."hsl(330, 50%, 50%)"); // 'hsl(330, 50%, 60%)'
changeLightness(-10."hsl(330, 50%, 50%)"); // 'hsl(330, 50%, 40%)'
Copy the code

Converts the HSL () color string to an array of values.

// Convert the HSL () color string to an array of values.
const toHSLArray = (hslStr) = > hslStr.match(/\d+/g).map(Number);

/ / use
toHSLArray("hsl(50, 10%, 10%)"); / / [50, 10, 10]
Copy the code

Converts the HSL () color string to an object with each color value.

// Convert the HSL () color string to an object with each color value.
const toHSLObject = (hslStr) = > {
  const [hue, saturation, lightness] = hslStr.match(/\d+/g).map(Number);
  return { hue, saturation, lightness };
};

/ / use
toHSLObject("hsl(50, 10%, 10%)"); // { hue: 50, saturation: 10, lightness: 10 }
Copy the code

The last

I am rongding, very happy to be here with you to become stronger! Programming for happiness together! 😉

If you love front-end technology too! Welcome to my front circle ~ 🦄 click → here