Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to generate a random color in javascript? [closed]

People also ask

What is the function of Getrandomcolor?

Answers related to “getrandomcolor”generates a random rgb color number.

How do you generate a random number in Javascript?

Javascript creates pseudo-random numbers with the function Math. random() . This function takes no parameters and creates a random decimal number between 0 and 1. The returned value may be 0, but it will never be 1.


A shorter way:

'#'+(0x1000000+Math.random()*0xffffff).toString(16).substr(1,6)

Here's a way to generate a random color and provide the minimum brightness:

function randomColor(brightness){
  function randomChannel(brightness){
    var r = 255-brightness;
    var n = 0|((Math.random() * r) + brightness);
    var s = n.toString(16);
    return (s.length==1) ? '0'+s : s;
  }
  return '#' + randomChannel(brightness) + randomChannel(brightness) + randomChannel(brightness);
}

Call randomColor with a value from 0-255, indicitating how bright the color should be. This is helpful for generating pastels, for example randomColor(220)


I like your second option, although it can be made a little bit simpler:

// Math.pow is slow, use constant instead.
var color = Math.floor(Math.random() * 16777216).toString(16);
// Avoid loops.
return '#000000'.slice(0, -color.length) + color;

I did it like this, with the help of other answers:

'#' + parseInt(Math.random() * 0xffffff).toString(16)

As George said the best way is to use HSL, so you can generate a bunch of random human-distinguishable colours. The similar idea is implemented in Adams Cole answer to the similar question, but his code have random color generator and hsl->hex rgb translator bundled together which makes it hard to understand and modify.

If you use one of the javascript color manipulation libraries (like jquery-color) color generation become trivial:

function rainbow() {
  // 30 random hues with step of 12 degrees
  var hue = Math.floor(Math.random() * 30) * 12;

  return $.Color({
    hue: hue,
    saturation: 0.9,
    lightness: 0.6,
    alpha: 1
  }).toHexString();
};

More succinct:

function get_random_color2() 
{
    var r = function () { return Math.floor(Math.random()*256) };
    return "rgb(" + r() + "," + r() + "," + r() + ")";
}

function randomColor()
{
     color='rgb('+Math.round(Math.random()*255)+','+Math.round(Math.random()*255)+','+Math.round(Math.random()*255)+')';

     return color;
}

This returns a random RGB value.