Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript, pick a random hex color between a start and end color

IS there any quick way of accomplishing this?

For example the start color #EEEEEE and end color #FFFFFF would make something like #FEFFEE.

like image 805
inControl Avatar asked Apr 24 '14 19:04

inControl


2 Answers

Of course the hex is encoded as a number but for it to make any kind of sense, you have to first extract the rgb components :

function rgb(string){
    return string.match(/\w\w/g).map(function(b){ return parseInt(b,16) })
}
var rgb1 = rgb("#EEEEEE");
var rgb2 = rgb("#FFFFFF");

Then simply take an intermediate of all components :

var rgb3 = [];
for (var i=0; i<3; i++) rgb3[i] = rgb1[i]+Math.random()*(rgb2[i]-rgb1[i])|0;

And finally rebuild the color as a standard hex string :

var newColor = '#' + rgb3
    .map(function(n){ return n.toString(16) })
    .map(function(s){ return "00".slice(s.length)+s}).join(''); 

Note that in order to get better results, depending on your goal, for example if you want to keep the luminosity, using a different color space than RGB (say HSL or HSV) might be useful.

like image 137
Denys Séguret Avatar answered Sep 28 '22 14:09

Denys Séguret


d3 does this extremely well by creating colour scales:

var color = d3.scale.linear()
    .domain([-1, 0, 1])
    .range(["red", "white", "green"]);

color(-1)   // "#ff0000" red
color(-0.5) // "#ff8080" pinkish
color(0)    // "#ffffff" white
color(0.5)  // "#80c080" getting greener
color(0.7)  // "#4da64d" almost there..
color(1)    // "#008000" totally green!
like image 33
Jivings Avatar answered Sep 28 '22 15:09

Jivings