Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a random seeded hex color?

I am using '#'+Math.floor(Math.random()*16777215).toString(16); to generate a random hex color on key press.

This is used to change the background color whenever a lowercase alpha key is pressed.

I want to alter this code to be seeded by the keycode. How can I do this?

I tried '#'+Math.floor(e.which*16777215).toString(16); but this generates a 7 character code instead of 6?

like image 865
Hailwood Avatar asked Nov 15 '11 05:11

Hailwood


People also ask

How do you generate a random hex color in python?

To generate a random hex color:Use the random. randint() method to get 3 random numbers from 0 to 255. Use a formatted string literal to format the digits in hex.


2 Answers

By saying you want a "seeded" random number I'm assuming you want the same color every time the same key is pressed. Unfortunately you can't control the Math.random() seed in JavaScript since it does not accept a seed as a parameter like in some other languages.

You could generate a random looking hex number with something like this:

Math.floor((Math.abs(Math.sin(seed) * 16777215))).toString(16);

This should generate an unique number for everything in the ASCII range, but some of the colors may very similar.

function genColor (seed) {
  color = Math.floor((Math.abs(Math.sin(seed) * 16777215)));
  color = color.toString(16);
  // pad any colors shorter than 6 characters with leading 0s
  while(color.length < 6) {
    color = '0' + color;
  }

  return color;
}

let tableHTML = '';

for (let i=32; i < 127; i++) {
  color = genColor(i);
  tableHTML += `<tr style="background:#${color}"><td>${String.fromCharCode(i)}</td><td>#${color}</td></tr>`;
}

tableHTML = `<table>${tableHTML}</table>`;

$('#test').bind('keypress', function (evt) {
    $(this).css('background', '#' + genColor(evt.which));

});
$('body').append(tableHTML);
#out, p, input { margin: 1em }
table {border-collapse: separate}
td {padding: 1em; border: 3px solid #fff; color: #fff; text-shadow: 0px 0px 3px #000}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="out">Type in the input box to change its background color :<input id="test">
    <p>Below is a list of colors generated for ASCII 32 through 126</p>
</div>
like image 130
Useless Code Avatar answered Sep 24 '22 03:09

Useless Code


You are getting a 7 letter code because you are working with a number that cannot be represented as 6 characters in hexadecimal.

16777215 (base 10) in base 16 is FFFFFF. If your decimal number grows any larger, another hexadecimal letter/digit will be used to express it.

To make your code work, just make sure 16777215 is the highest.

222 seems to be the highest keycode possible (please correct me if I am mistaken):

Math.floor(e.which * 16777215 / 222).toString(16);
like image 44
Blender Avatar answered Sep 25 '22 03:09

Blender