0

I have the following method

export const generateRandomColor = () => {
  const letters = "0123456789ABCDEF";
  let color = "#";

  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * letters.length)];
  }

  return color;
};

which generates random colors. I am using this function to get the colors of my PieChart, and definitely, it is not elegant at all to see colors of different types (light, dark, pastels...) mixed.

How can I only generate random PASTEL colors in JS (HEX or RGBA)?

Victor Molina
  • 2,353
  • 2
  • 19
  • 49

2 Answers2

3

To generate a range of color with pastel ton like, you can generate each canal with minimal value of 127:

generatePastelColor = () => {
  let R = Math.floor((Math.random() * 127) + 127);
  let G = Math.floor((Math.random() * 127) + 127);
  let B = Math.floor((Math.random() * 127) + 127);
  
  let rgb = (R << 16) + (G << 8) + B;
  return `#${rgb.toString(16)}`;      
}

document.querySelectorAll('#palette div').forEach( elem => {
  elem.style.backgroundColor = generatePastelColor();
});
#palette {
  width: 100px;
  height: 100px;
}

#palette > div {
  width: 100%;
  height: 20px;
}
<div id="palette">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
thibsc
  • 3,747
  • 2
  • 18
  • 38
1

React Native seems to support hsl according to the docs. If that works for you, then this answer may be of some help.