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).

2
  • Is this a homework question? Commented Dec 8, 2014 at 20:44
  • What is your brightness threshold? You would basically try to determine if each pair of hex numbers are < ff and > some brightness threshold or 00. Commented Dec 8, 2014 at 20:54

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Not one-liner, but this code is more clear and readable. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.