21

是否可以计算渐变中间的颜色?

var color1 = 'FF0000';
var color2 = '00FF00';

// 50% between the two colors, should return '808000'
var middle = gradient(color1, color2, 0.5); 

我只有两个十六进制字符串,我想要一个作为回报。

4

4 回答 4

45

这应该有效:

它基本上涉及将它们转换为十进制,找到一半,将结果转换回十六进制,然后将它们连接起来。

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);
于 2013-05-03T13:57:15.743 回答
4

我无法评论上面的答案,所以我写在这里:

我发现在 Javascript 子字符串方法中,返回的字符串中不包含 to 参数索引。这意味着:

var string = "test";
//index:      0123
alert(string.substring(1,3));

//will alert es and NOT est

编辑:所以它应该是:

parseInt(color1.substring(0,2), 16);
parseInt(color1.substring(2,4), 16);

parseInt(color1.substring(4,6), 16);
于 2013-05-06T17:13:56.493 回答
3

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

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

  • 前两行将颜色代码转换为缩放整数数组
  • 第三行:
    • “压缩”两个整数数组
    • 对相应的值求和
    • 将总和四舍五入并将其限制为 0-255
  • 第四行:
    • 将整数数组转换为单个整数(减少和位移)
    • 将整数转换为其十六进制字符串形式
    • 确保生成的字符串长度为 6 个字符并返回它
于 2020-09-07T09:54:53.280 回答
2

你可以使用这个准备好的函数(ES6):

const calculateMiddleColor = ({
  color1 = 'FF0000',
  color2 = '00FF00',
  ratio,
}) => {
  const hex = (color) => {
    const colorString = color.toString(16);
    return colorString.length === 1 ? `0${colorString}` : colorString;
  };

  const r = Math.ceil(
    parseInt(color2.substring(0, 2), 16) * ratio
      + parseInt(color1.substring(0, 2), 16) * (1 - ratio),
  );
  const g = Math.ceil(
    parseInt(color2.substring(2, 4), 16) * ratio
      + parseInt(color1.substring(2, 4), 16) * (1 - ratio),
  );
  const b = Math.ceil(
    parseInt(color2.substring(4, 6), 16) * ratio
      + parseInt(color1.substring(4, 6), 16) * (1 - ratio),
  );

  return hex(r) + hex(g) + hex(b);
};
//////////////////////////////////////////////////////////////////////
console.log(calculateMiddleColor({ ratio: 0 / 5 })); // ff0000
console.log(calculateMiddleColor({ ratio: 5 / 5 })); // 00ff00
console.log(calculateMiddleColor({ ratio: 2.5 / 5 })); // 808000
console.log(calculateMiddleColor({ ratio: 4.2 / 5 })); // 29d700
于 2019-12-21T23:12:27.073 回答