How do you get random RGB in Javascript?

ipodlover3354 picture ipodlover3354 · Apr 16, 2014 · Viewed 42k times · Source

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.

Answer

adeneo picture adeneo · Apr 16, 2014
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