0

at the moment I have this code to generate a random color:

let color = Math.floor(Math.random() * 16777216).toString(16);
color = '#000000'.slice(0, -color.length) + color;
department.color = color;

but what I want is to genertae a random "tint" color , what should I add/change to make it work...?

Caramiriel
  • 7,029
  • 3
  • 30
  • 50
pb4now
  • 1,305
  • 4
  • 18
  • 45
  • Can you be clearer about what you mean by random tint? Do you want colors selected randomly from the same range of hues? Or are you looking for a variety of hues all sharing a similar saturation and lightness, etc...? – Mark Dec 04 '17 at 19:07
  • @Mark_M ' variety of hues all sharing a similar saturation and lightness, ' :) – pb4now Dec 04 '17 at 19:12

1 Answers1

1

If you can just use hsl() for your colors, that will be the easiest. You can just set your hue to a random value and set your saturation and lightness constant (or a small range).

If you need rgb strings, you can use the standard HSL->RGB conversion found here and elsewhere to make the rgb string.

let [sat, lightness] = [.6, .8]
let container = document.getElementById("colors")
for (let i = 0; i < 12; i++) {
  let hue = Math.random()
  let block = document.createElement('div');
  block.className = 'colorbrick';
  block.style.backgroundColor = hslToRgb(hue, sat,lightness);
  container.appendChild(block)
}

function hslToRgb(h, s, l) {
  let r, g, b;
  if (s == 0) {
    r = g = b = l;
  } else {
    function hue2rgb(p, q, t) {
      if (t < 0) t += 1;
      if (t > 1) t -= 1;
      if (t < 1 / 6) return p + (q - p) * 6 * t;
      if (t < 1 / 2) return q;
      if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
      return p;
    }
    var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
    var p = 2 * l - q;
    r = hue2rgb(p, q, h + 1 / 3);
    g = hue2rgb(p, q, h);
    b = hue2rgb(p, q, h - 1 / 3);
  }
  return "#" + [r * 255, g * 255, b * 255].map(c => Math.floor(c).toString(16)).join('');
};
.colorbrick {
  display: inline-block;
  width: 80px;
  height: 80px;
  margin: 6px;
}
<div id="colors">
</div>
Mark
  • 90,562
  • 7
  • 108
  • 148