Javascript, choose random hex color between start and end color

Is there any quick way to do this?

For example, the starting color #EEEEEE and the ending color #FFFFFF will do something like #FEFFEE.

+4
source share
4 answers

Of course, the hex code is encoded as a number, but in order to make any sense, you must 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 just take the intermediate link from all the 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 hexadecimal string:

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

, , , , , , RGB (, HSL HSV).

+10

d3 , :

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!
+1

, , . ( ). .

:

for(var i = 0;i < 6; i++) {
    color += (Math.floor(Math.random() * (end-start+1)) + start).toString(16);
}

0 15

:

for(var i = 0;i < 3; i++) {
    color += (Math.floor(Math.random() * (end-start+1)) + start).toString(16);
}

0 255

0

Try:

function getRandomColor(start, end){
    var min=parseInt(start.replace("#",""), 16);
    var max=parseInt(end.replace("#",""), 16);
    return "#"+Math.floor((Math.random() * (max - min) + min)).toString(16).toUpperCase();
}    

Fiddle.

-1

Source: https://habr.com/ru/post/1537950/


All Articles