计算具有2种颜色和百分比/位置的颜色HEX

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)


jed*_*rds 7

带有推导式的 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)

正如在接受的答案中一样,c0c1颜色代码(没有前导#),f是两个值之间的“进度”。(f=0此时最终返回c0f=1此时返回c1)。

  • 前两行将颜色代码转换为缩放整数数组
  • 第三行:
    • “压缩”两个整数数组
    • 对相应的值求和
    • 对总和进行四舍五入并将其限制为 0-255
  • 第四行:
    • 将整数数组转换为单个整数(归约和位移位)
    • 将整数转换为其十六进制字符串形式
    • 确保结果字符串的长度为 6 个字符并返回