在javascript中平均2个十六进制颜色

sam*_*one 14 javascript hex colors

好吧,我想把这个扔到那里供人群思考.

给定一个函数 (用javascript编写),期望两个字符串形成像十六进制颜色(ex#FF0000)

返回一个十六进制颜色,它是两种颜色的平均值.

function averageColors(firstColor,secondColor)
{
  ...
  return avgColor;
}
Run Code Online (Sandbox Code Playgroud)

- 编辑 -

平均值将被定义为 在此输入图像描述

如果通过的颜色是黄色而第二个是浅紫色,则返回的颜色将是中等橙色

Mat*_*all 18

我恨听起来像的哦,所以,破纪录的jQuery,但有一个jQuery插件本已.

$ .xcolor.average(颜色,颜色)


V. *_*tti 9

按指定百分比混合两种十六进制颜色的快速/脏/方便/ES6 方式:

// blend two hex colors together by an amount
function blendColors(colorA, colorB, amount) {
  const [rA, gA, bA] = colorA.match(/\w\w/g).map((c) => parseInt(c, 16));
  const [rB, gB, bB] = colorB.match(/\w\w/g).map((c) => parseInt(c, 16));
  const r = Math.round(rA + (rB - rA) * amount).toString(16).padStart(2, '0');
  const g = Math.round(gA + (gB - gA) * amount).toString(16).padStart(2, '0');
  const b = Math.round(bA + (bB - bA) * amount).toString(16).padStart(2, '0');
  return '#' + r + g + b;
}

console.log(blendColors('#00FF66', '#443456', 0.5));
Run Code Online (Sandbox Code Playgroud)

amount010确切地说colorA1确切地说colorB,并0.5作为“中点”。


Rob*_*obG 8

如果你不想打扰很多不必要的东西,只需要几行POJS:

// Expects input as 'nnnnnn' where each nn is a 
// 2 character hex number for an RGB color value
// e.g. #3f33c6
// Returns the average as a hex number without leading #
var averageRGB = (function () {

  // Keep helper stuff in closures
  var reSegment = /[\da-z]{2}/gi;

  // If speed matters, put these in for loop below
  function dec2hex(v) {return v.toString(16);}
  function hex2dec(v) {return parseInt(v,16);}

  return function (c1, c2) {

    // Split into parts
    var b1 = c1.match(reSegment);
    var b2 = c2.match(reSegment);
    var t, c = [];

    // Average each set of hex numbers going via dec
    // always rounds down
    for (var i=b1.length; i;) {
      t = dec2hex( (hex2dec(b1[--i]) + hex2dec(b2[i])) >> 1 );

      // Add leading zero if only one character
      c[i] = t.length == 2? '' + t : '0' + t; 
    }
    return  c.join('');
  }
}());
Run Code Online (Sandbox Code Playgroud)


nag*_*eeb 6

闻起来像我的作业,但这是我的线索.

获取R,G和B的每个十六进制值,并对它们进行平均.如有必要,转换为Decimal进行数学运算.

function d2h(d){return d.toString(16).padStart(2,'0');}

function h2d(h){return parseInt(h,16);}

然后返回一个包含三个元素的连接值的字符串.