How do you get random RGB in Javascript? [duplicat

2020-05-26 03:54发布

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.

3条回答
对你真心纯属浪费
2楼-- · 2020-05-26 04:33
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

查看更多
够拽才男人
3楼-- · 2020-05-26 04:43

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.

查看更多
一纸荒年 Trace。
4楼-- · 2020-05-26 04:47
var r = Math.floor(Math.random()*256);          // Random between 0-255
var g = Math.floor(Math.random()*256);          // Random between 0-255
var b = Math.floor(Math.random()*256);          // Random between 0-255
var rgb = 'rgb(' + r + ',' + g + ',' + b + ')'; // Collect all to a string
查看更多
登录 后发表回答