Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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(/ww/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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...