Generate a Random Color in JavaScript

This is a simple example of how to generate random colors in RGB, RGBA, and Hex formats in JavaScript.

Feel free to use this as a starting point for your own projects!(Credits are appreciated, but not required.)

Random RGB Color in JavaScript

const randomRgbColor = () => {
  const r = Math.floor(Math.random() * 256);
  const g = Math.floor(Math.random() * 256);
  const b = Math.floor(Math.random() * 256);
  return `rgb(${r}, ${g}, ${b})`;
};

// Example
console.log(randomRgbColor()); // "rgb(22, 123, 4)"

Random RGBA Color in JavaScript

const randomRgbaColor = () => {
  const r = Math.floor(Math.random() * 256);
  const g = Math.floor(Math.random() * 256);
  const b = Math.floor(Math.random() * 256);
  const a = Math.random(); // 0.0 - 1.0
  return `rgba(${r}, ${g}, ${b}, ${a.toFixed(2)})`;
};

// Example
console.log(randomRgbaColor()); // "rgba(22, 123, 4, 0.83)"

Random Hex Color in JavaScript

const randomHexColor = () => {
  // Generate a random 2 digit hex number, padded with a 0 if necessary
  const part = () =>
    Math.floor(Math.random() * 256)
      .toString(16)
      .padStart(2, '0');
  const r = part();
  const g = part();
  const b = part();
  return `#${r}${g}${b}`;
};

// Example
console.log(randomHexColor()); // "#7f0aa3"
© 2023
Random Color Generator
|
Privacy Policy