Monday, August 26, 2013

Get a random color in JavaScript

Computer can understand only hexadecimal color code.

As a science student, you might be known.
Converting a base(x) number to base(n) number.

Same logic we are going to use. In JavaScript we have base conversions.

Math.random() will return a float number. Convert this number to integer as well string too.
While your converting string pass "16" parameter to toString(16) function. So, this way it converts a string to base(16) number.

 Solution :  
1. '#'+Math.floor((Math.random()*100000000)).toString(16)
2.  '#'+(( 1<<24)*Math.random()|0).toString(16)

This function will hep you to generate number of colors as you given input number

var getRandomColors = function(no){
    no = no || 0;
    no = parseInt(no,10);
    var i=0,arr=[];
    do{
        arr.push( "#"+(( 1<<24)*Math.random()|0).toString(16) );
        i++;
    }while (i < no);
    return arr;
}

Friday, March 1, 2013