Kal*_*iwy 12 javascript jquery gradient colors
是否可以计算渐变中间的颜色?
var color1 = 'FF0000';
var color2 = '00FF00';
// 50% between the two colors, should return '808000'
var middle = gradient(color1, color2, 0.5);
Run Code Online (Sandbox Code Playgroud)
我只有两个十六进制字符串,我想要一个作为回报.
tec*_*bar 37
这应该工作:
它基本上涉及将它们转换为十进制,找到一半,将结果转换回十六进制,然后连接它们.
var color1 = 'FF0000';
var color2 = '00FF00';
var ratio = 0.5;
var hex = function(x) {
x = x.toString(16);
return (x.length == 1) ? '0' + x : x;
};
var r = Math.ceil(parseInt(color1.substring(0,2), 16) * ratio + parseInt(color2.substring(0,2), 16) * (1-ratio));
var g = Math.ceil(parseInt(color1.substring(2,4), 16) * ratio + parseInt(color2.substring(2,4), 16) * (1-ratio));
var b = Math.ceil(parseInt(color1.substring(4,6), 16) * ratio + parseInt(color2.substring(4,6), 16) * (1-ratio));
var middle = hex(r) + hex(g) + hex(b);
Run Code Online (Sandbox Code Playgroud)
带有推导式的 ES6 版本:
function interpolateColor(c0, c1, f){
c0 = c0.match(/.{1,2}/g).map((oct)=>parseInt(oct, 16) * (1-f))
c1 = c1.match(/.{1,2}/g).map((oct)=>parseInt(oct, 16) * f)
let ci = [0,1,2].map(i => Math.min(Math.round(c0[i]+c1[i]), 255))
return ci.reduce((a,v) => ((a << 8) + v), 0).toString(16).padStart(6, "0")
}
Run Code Online (Sandbox Code Playgroud)
正如在接受的答案中一样,c0
是c1
颜色代码(没有前导#
),f
是两个值之间的“进度”。(f=0
此时最终返回c0
,f=1
此时返回c1
)。