30

I have this code that uses RGB color selection and I was wondering how to make JavaScript do a random color using the RGB method and remember it throughout the code.

EDIT: I tried this:

var RGBColor1 = (Math.round, Math.random, 255)
var RGBColor2 = (Math.round, Math.random, 255)
var RGBColor3 = (Math.round, Math.random, 255)

but it doesn't work. Help please!

EDIT 2: The code uses this:

g.fillStyle="rgba(R,G,B,0.2)";
g.strokeStyle="rgba(R,G,B,0.3)";
E();

The letters represent the color of RGB.

EDIT 3: The doubles of this question are using HEX values, not RGB values.

ROOT
  • 11,363
  • 5
  • 30
  • 45
ipodlover3354
  • 449
  • 1
  • 4
  • 11
  • Generate three random numbers (in the range of 0 to 255), insert them into a string (format `"rgb(n1, n2, n3)"`) and assign that to a variable. Where are you stuck? – David Thomas Apr 15 '14 at 22:26

3 Answers3

66
function random_rgba() {
    var o = Math.round, r = Math.random, s = 255;
    return 'rgba(' + o(r()*s) + ',' + o(r()*s) + ',' + o(r()*s) + ',' + r().toFixed(1) + ')';
}

var color = random_rgba();

g.fillStyle   = color;
g.strokeStyle = color;

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
31
const randomBetween = (min, max) => min + Math.floor(Math.random() * (max - min + 1));
const r = randomBetween(0, 255);
const g = randomBetween(0, 255);
const b = randomBetween(0, 255);
const rgb = `rgb(${r},${g},${b})`; // Collect all to a css color string
assembly_wizard
  • 2,034
  • 1
  • 17
  • 10
21

Here's a very simple method that works off of a single random number generation. Basically, it generates a number between 0 and 0xfffff (or 2^24, the highest number you can get from 24 bits). The highest value you can get from 8 bits is 255. This algorithm takes the left-most 8 bits of the random number for RED, the middle 8 bits for GREEN, and the last 8 bits for BLUE, using all 24 bits of the random number.

function getRandomRgb() {
  var num = Math.round(0xffffff * Math.random());
  var r = num >> 16;
  var g = num >> 8 & 255;
  var b = num & 255;
  return 'rgb(' + r + ', ' + g + ', ' + b + ')';
}

for (var i = 0; i < 10; i++) {
  console.log(getRandomRgb());
}

Console output (sample):

rgb(2, 71, 181)
rgb(193, 253, 111)
rgb(172, 127, 203)
rgb(203, 53, 175)
rgb(226, 45, 44)
rgb(102, 181, 19)
rgb(92, 165, 221)
rgb(250, 40, 162)
rgb(250, 252, 120)
rgb(67, 59, 246) 

Adapted from source.

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
  • Somewhere you will need `var randomRgb = getRandomRgb();`. Then use `randomRgb` wherever you need it. I leave how to scope it all to you, since I have no idea how to actually incorporate it into your current code. – Cᴏʀʏ Apr 15 '14 at 22:39
  • 2
    +1 for doing just one random number generation. – jfriend00 Apr 15 '14 at 22:45
  • 1
    Agreed; it's beautiful: but *I have no idea how it works..!* – David Thomas Apr 15 '14 at 22:56