random rgb color generator in javascript

Here's a simple code snippet that generates a random RGB color in JavaScript:

index.tsx
function getRandomColor() {
  var r = Math.floor(Math.random() * 256);
  var g = Math.floor(Math.random() * 256);
  var b = Math.floor(Math.random() * 256);
  return "rgb(" + r + ", " + g + ", " + b + ")";
}

// Example usage:
var randomColor = getRandomColor(); // rgb(135, 197, 76)
284 chars
10 lines

Explanation:

  • We define a function called getRandomColor that takes no parameters.
  • Inside the function, we use the Math.random() method to generate random numbers between 0-255 for each value of red, green, and blue.
  • We concatenate the RGB values into a string and return it.
  • Example usage: We call the function and store the returned RGB string in a variable called randomColor.

You can then use this random color for various purposes, such as setting the background color of an element.

gistlibby LogSnag