问题描述
有没有快速的方法可以做到这一点?
IS there any quick way of accomplishing this?
例如,开始颜色#EEEEEE和结束颜色#FFFFFF类似于#FEFFEE。
For example the start color #EEEEEE and end color #FFFFFF would make something like #FEFFEE.
推荐答案
当然,十六进制编码为数字,但要使其具有某种意义,则必须首先提取rgb分量:
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('');
请注意,为了获得更好的结果,具体取决于您的目标,例如是否要保留使用与RGB(例如HSL或HSV)不同的可以提高亮度。
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.
这篇关于javascript,在开始和结束颜色之间选择随机的十六进制颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!