1

Given the following code to generate random colors (credit):

'#'+((1<<24)*(Math.random()+1)|0).toString(16).substr(1)

What conditions can be added to this code, in order to make it produce only bright colors but darker than pure white #ffffff.

The elements which are assigned these colors, need to be displayed on a dark background (#111).

Community
  • 1
  • 1
Annie
  • 3,090
  • 9
  • 36
  • 74

1 Answers1

2

Rather than messing with the bitwise left-shift, it's probably easier to generate each digit separately, like so:

var color = '#';
for (var i = 0; i < 3; i+=1) {
  var first = Math.floor((Math.random()*8+8)).toString(16);
  var second = Math.floor((Math.random()*16)).toString(16);

  color = color + first + second;
}

If you want to adjust exactly how light/dark the colors are, change the Math.random()*8+8 to adjust the first digit in each of the R, G, B values. As it stands, this will generate anything from #808080 to #ffffff. If you wanted from #a0a0a0 to #ffffff, change it *10+6 - it can be anything in the form *x+y so long as x and y add up to 16.

Cara McCormack
  • 388
  • 1
  • 7
  • 21