How do you get random RGB in Javascript? [duplicate] How do you get random RGB in Javascript? [duplicate] javascript javascript

How do you get random RGB in Javascript? [duplicate]


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


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


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());}