DEV Community

Prakhar Tandon
Prakhar Tandon

Posted on • Updated on

Different possible methods for generating a colour randomly in JS

In this post, I will be summarising several possible methods for generating a colour randomly in JavaScript.
So, Save this article !
As you might be aware of how colours are represented, i.e, Hexadecimal code with a '#' prefix --> #RRGGBB
The code for Black --> #000000
and for white --> #ffffff
Hence higher the values, more the colour will be lighter and vice-versa.
Here's the different methods:

  • Method 1 In this approach, simply take a string of all possible hexadecimal characters, then choose from it randomly and concatenate them to form a 6 digit hex code.
const s = "0123456789ABCDEF";
function getRandomColor() 
{
    let col = "#";
    let temp =0;
    for(let i=0;i<6;++i)
    {
       temp = Math.floor( Math.random() * s.length ); // generates number between 0-15
       col = col + s[temp];
    }
return col;
}
Enter fullscreen mode Exit fullscreen mode

for generating lighter/Darker colours only, we can use sLight or sDark respectively.

const sLight="789ABCDEF";
const sDark="01234567";
Enter fullscreen mode Exit fullscreen mode
  • Method 2 Similar to the first one but here instead of predefined string, we can use toString(16) to convert to HexaDecimal.
function getRandomColor(){
    let color = "#";
    for(let i=0;i<6;++i)
        color += (Math.floor( Math.random() * 16 ).toString(16) );
    return color;
}
Enter fullscreen mode Exit fullscreen mode
  • Method 3 We can use the following ES6 approach :
const getRandomHex = from => to => () =>
    Math.floor(Math.random() * (to - from) + from).toString(16);

const getRangedRandomColor = from => to => () =>
    `#${[...Array(6)].map(getRandomHex(from)(to)).join("")}`;

const getRandomColor = getRangedRandomColor(0x0)(0xf);
const getRandomColorLight = getRangedRandomColor(0x7)(0xf);
const getRandomColorDark = getRangedRandomColor(0x0)(0x7);
Enter fullscreen mode Exit fullscreen mode

Thanks to @lukeshiru for this one, and you can find the detailed explaination for this in the comments section of my previous article here

  • Method 4
function getRandomColor() {
    function c() {
      var hex = Math.floor(Math.random()*256).toString(16);
      return ("0"+String(hex)).substr(-2); // pad with zero
    }
    return "#"+c()+c()+c();
}
Enter fullscreen mode Exit fullscreen mode

substr(-2) means take last two characters of the string.

  • Method 5 This one is a great one liner for the same I found on StackOverflow.
function getRandomColor() {
    return '#'+(Math.random().toString(16)+'00000').slice(2,8);
}
Enter fullscreen mode Exit fullscreen mode

Well these were some of my picks, if you want to dive in more, you can have a look at this thread on StackOverFlow.

You can save this article for future references and comment down your opinions as well !

You can follow me on:
Twitter
GitHub

Discussion (4)

Collapse
lukeshiru profile image
Luke Shiru

Thanks for the credit!

About this post, something that might be useful for you: To pad zeroes to a string, you can use the native String.prototype.padStart instead of concatenating "0" and then slicing. Here are the examples:

For method 4:

function getRandomColor() {
    function c() {
        return Math.floor(Math.random() * 256)
            .toString(16)
            .padStart(2, "0");
    }
    return "#" + c() + c() + c();
}
Enter fullscreen mode Exit fullscreen mode

And if we take it one step further:

const getRandomHex = () =>
    Math.floor(Math.random() * 0xff)
        .toString(16)
        .padStart(2, "0");

const getRandomColor = () =>
    `#${getRandomHex()}${getRandomHex()}${getRandomHex()}`;
Enter fullscreen mode Exit fullscreen mode

For method 5:

function getRandomColor() {
    return "#" + Math.random().toString(16).slice(2, 8).padStart(6, "0");
}
Enter fullscreen mode Exit fullscreen mode

And also taking it one step further:

const getRandomColor = () =>
    `#${Math.random().toString(16).slice(2, 8).padStart(6, "0")}`;
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
prakhart111 profile image
Prakhar Tandon Author • Edited on

Okay great, well that's the benefit of an active community, you learn everyday!
And your comments just enhance my article thanks for this
and Cheers!

Collapse
rpm profile image
Ryan McCormick • Edited on

Not a random color exactly, but here is code I wrote that produces a nice pastel color from any string, and will always be the same for that same string (it actually only uses the first 2 and last letters of the string).

  //--- START Helper Functions ------------------------------------------------\\
  function Colorize(seed = 'AA')
   {//Returns a pastel color based on 1st, 2nd, and Last characters in a string.
    if (seed.length = 0) {seed = 'AA';} else
    if (seed.length = 1) {seed += 'A';}
    r = (seed.charCodeAt(0) * 9).toString(16).slice(-2);
    g = (seed.charCodeAt(1) * 9).toString(16).slice(-2);
    b = (seed.charCodeAt(seed.length-1) * 9).toString(16).slice(-2);
    return '#'+r+g+b;
   }
  //----------------------------------------------------------------------------
Enter fullscreen mode Exit fullscreen mode

I use it to color-code categories, even when the user can enter their own categories.

Collapse
lukeshiru profile image
Luke Shiru

There are a few typos in your function. The ifs are not comparing, they are assigning to seed.length. Also r, g and b are being defined globally. Here is the fix:

function Colorize(seed = "AA") {
    if (seed.length === 0) {
        seed = "AA";
    } else if (seed.length === 1) {
        seed += "A";
    }
    const r = (seed.charCodeAt(0) * 9).toString(16).slice(-2);
    const g = (seed.charCodeAt(1) * 9).toString(16).slice(-2);
    const b = (seed.charCodeAt(seed.length - 1) * 9).toString(16).slice(-2);
    return "#" + r + g + b;
}
Enter fullscreen mode Exit fullscreen mode

And if you want to take it one step further:

const stringToColor = (seed = "") =>
    (paddedSeed =>
        `#${[
            paddedSeed.charCodeAt(0),
            paddedSeed.charCodeAt(Math.floor(paddedSeed.length / 2)),
            paddedSeed.charCodeAt(paddedSeed.length - 1),
        ]
            .map(value => (value * 9).toString(16).slice(-2))
            .join("")}`)(seed.padEnd(3, "A"));

Enter fullscreen mode Exit fullscreen mode

Cheers!