Javascript code to generate random color

Javascript code to generate random color 


There are many ways to generate random color in javascript .Some of the ways to generate random colors are listed below:

 

1.First Method

This is the first method as well as the shortest and the fastest way to generate random color.You can generate random color using this within seconds in a single sentence of javascript. Here,Math.floor(Math.random()*16777215).toString(16) gnerates a random string of alphabets and numbers of 6 characters and the # is added before it to generate random rgb color.

var randomColor = '#' + Math.floor(Math.random()*16777215).toString(16);
console.log(randomColor)

2.Second Method

This is the second method of generating random color in js.Here,we have just broke the previous code in small modules and declared some variables in the code and made it easy to memorize and understand for the programmer and the debugger.

let hexString = "0123456789abcdef";
let hexCode = "#";
for( i = 0; i < 6; i++){
    hexCode += hexString[Math.floor(Math.random() * hexString.length)];
}
console.log(hexCode)

3.Third Method

const arrayOfColorFunctions = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']

let randomColorString = '#';
function newColorFind(){

for (let x = 0; x < 6; x++){

    let index = Math.floor(Math.random() * 16)
    let value = arrayOfColorFunctions[index]

    randomColorString += value
}
 console.log(randomColorString)


}

4.Forth Method

var x=Math.round(0xffffff * Math.random()).toString(16);
var y=(6-x.length);
var z='000000';
var z1 = z.substring(0,y);
var color= “#” + z1 + x;

console.log(color)
}

5.Fifth Method

const randomColor =  '#' +Math.floor(Math.random() * 2 ** 24).toString(16).padStart(6, “0”);
console.log(randomColor)
}

6.Sixth Method

var color='#'+ Math.floor(Math.random()*8**8).toString(16);
console.log(color)
}

Post a Comment

0 Comments