Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I'm trying to generate random hexadecimal colors between this range: min= #00FF00 (green) and max= #FF0000 (red).


What I have tried:

I made my own search but I found only how to generate random hexadecimal colors not between two hexadecimal values (min and max).
Posted
Updated 18-Aug-21 0:27am
Comments
[no name] 18-Aug-21 15:04pm    
If you're going to derive your colors from ARGB, it's intuitively simpler to work with the 2 colors individually; and using integers.

public static System.Drawing.Color FromArgb (int alpha, int red, int green, int blue);

1 solution

Generate a random number between 65280 (0x00ff00) and 16711680 (0xff0000).
Math.random() - JavaScript | MDN[^]
JavaScript
function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}

const minValue = 0x00ff00;
const maxValue = 0xff0000;
let randomValue = getRandomInt(minValue, maxValue + 1);

Convert that number to hexadecimal:
JavaScript
let randomColor = "#" + randomValue.toString(16);
And that's your random colour.

Demo[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900