Skip to main content

Archive

Show more

How to generate random rgb color using javascript

how-to-generate-random-rgb-color-using-javascript


Question: How to generate random rgb color using javascript

Answer: We will talk about two methods to create random RGB color. We have solve one similar query that is 'How To Generate a Random Color in JavaScript', you can read that solution.


First Method:

function randomRGB() {
  var x = Math.floor(Math.random() * 256);
  var y = Math.floor(Math.random() * 256);
  var z = Math.floor(Math.random() * 256);
  var RGBColor = "rgb(" + x + "," + y + "," + z + ")";  
  console.log(RGBColor);
}

randomRGB();

Output: Your and our answer may or may not match as it is randomly generated.

"rgb(89,95,232)"





Second Method:

function randomRGB() {
  var roundValue = Math.round, rndmValue = Math.random, maxNum = 255;
  return 'rgba(' + roundValue(rndmValue()*maxNum) + ',' + roundValue(rndmValue()*maxNum) + ',' + roundValue(rndmValue()*maxNum) + ')';
}

console.log(randomRGB());

Output: Your and our answer may or may not match as it is randomly generated.

"rgb(245,15,82)"


We try to provide you the best content, if there is any mistake in this article or there is any mistake in code, then let us know.

Comments

  1. let randomRGB = `rgb(${Math.floor(Math.random()*255)},${Math.floor(Math.random()*255)},${Math.floor(Math.random()*255)})`;
    console.log(randomRGB); // -> rgb(239,181,96) / rgb(179,168,38) / rgb(24,22,80) / rgb(193,223,168) etc.

    ReplyDelete

Post a Comment