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

时间:2011-06-16 04:09:55

标签: javascript colors hex

好吧我以为我会把这个扔到那里供人群思考。

鉴于函数 (用javascript编写),需要两个字符串格式化为十六进制颜色( ex#FF0000

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

function averageColors(firstColor,secondColor)
{
  ...
  return avgColor;
}

- 编辑 -

平均值将定义为enter image description here

如果传递的颜色为黄色,第二种颜色为浅紫色,则返回的颜色为中橙色

8 个答案:

答案 0 :(得分:18)

我讨厌听起来像是破旧的jQuery记录,但 a jQuery plugin for this already

$.xcolor.average(color, color)

答案 1 :(得分: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('');
  }
}());

答案 2 :(得分:6)

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

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

  

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

     

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

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

答案 3 :(得分:0)

这是我的功能,希望它有所帮助。

function averageColors( colorArray ){
    var red = 0, green = 0, blue = 0;

    for ( var i = 0; i < colorArray.length; i++ ){
        red += hexToR( "" + colorArray[ i ] + "" );
        green += hexToG( "" + colorArray[ i ] + "" );
        blue += hexToB( "" + colorArray[ i ] + "" );
    }

    //Average RGB
    red = (red/colorArray.length);
    green = (green/colorArray.length);
    blue = (blue/colorArray.length);

    console.log(red + ", " + green + ", " + blue);
    return new THREE.Color( "rgb("+ red +","+ green +","+ blue +")" );
}

//get the red of RGB from a hex value
function hexToR(h) {return parseInt((cutHex( h )).substring( 0, 2 ), 16 )}

//get the green of RGB from a hex value
function hexToG(h) {return parseInt((cutHex( h )).substring( 2, 4 ), 16 )}

//get the blue of RGB from a hex value
function hexToB(h) {return parseInt((cutHex( h )).substring( 4, 6 ), 16 )}

//cut the hex into pieces
function cutHex(h) {if(h.charAt(1) == "x"){return h.substring( 2, 8 );} else {return h.substring(1,7);}}

答案 4 :(得分:0)

对于任何想要快速/脏/方便/ es6方式混合一定量的两种十六进制颜色的人(很可能是我未来的自我),请尝试以下方法:

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));
    let r = (rA + (rB - rA) * amount).toString(16).padStart(2, '0');
    let g = (gA + (gB - gA) * amount).toString(16).padStart(2, '0');
    let b = (bA + (bB - bA) * amount).toString(16).padStart(2, '0');
    return '#' + r + g + b;
}

amount应该是01,其中0正好是colorA1正好是colorB,并且0.5是“中点”。

答案 5 :(得分:0)

这是功能

"COOP_DAYEND"

要检查您可以使用此链接和中点1,然后进行融合 https://meyerweb.com/eric/tools/color-blend/#CC0D73:0000FF:1:hex

答案 6 :(得分:0)

这次聚会来晚了,但是我个人正在寻找一种方法来对未定义的十六进制值进行平均。基于答案@RobG,我想到了这个。当然,添加的颜色越多,它们得到的棕色/灰色就越多,但是也许有帮助!

/**
 * Averages an array of hex colors. Returns one hex value (with leading #)
 *
 * @param {Array} colors - An array of hex strings, e.g. ["#001122", "#001133", ...]
 */
function averageHex(colors) {

  // transform all hex codes to integer arrays, e.g. [[R, G, B], [R,G,B], ...]
  let numbers = colors.map(function(hex) {
    // split in seperate R, G and B
    let split = hex.match(/[\da-z]{2}/gi);

    // transform to integer values
    return split.map(function(toInt) {
      return parseInt(toInt, 16);
    });
  });

  // reduce the array by averaging all values, resulting in an average [R, G, B]
  let averages = numbers.reduce(function(total, amount, index, array) {
    return total.map(function(subtotal, subindex) {

      // if we reached the last color, average it out and return the hex value
      if (index == array.length - 1) {

        let result = Math.round((subtotal + amount[subindex]) / array.length).toString(16);

        // add a leading 0 if it is only one character
        return result.length == 2 ? '' + result : '0' + result;

      } else {
        return subtotal + amount[subindex];
      }
    });
  });

  // return them as a single hex string
  return "#" + averages.join('');
}

console.log(averageHex(["#FF110C", "#0000AA", "#55063d", "#06551e"]));
// expected: #571b44, see also https://www.colorhexa.com/ and enter "#FF110C+#0000AA+#55063d+#06551e"

答案 7 :(得分:0)

这是一组紧凑的相关(相互依赖)函数:

Hex ⟷ RGB 颜色转换:

function hexToRgb(h){return['0x'+h[1]+h[2]|0,'0x'+h[3]+h[4]|0,'0x'+h[5]+h[6]|0]}
function rgbToHex(r,g,b){return"#"+((1<<24)+(r<<16)+(g<<8)+ b).toString(16).slice(1);}

计算 2 种十六进制颜色的平均值:需要转换函数(上)

function avgHex(h1,h2){a=hexToRgb(h1);b=hexToRgb(h2); return rgbToHex(~~((a[0]+b[0])/2),~~((a[1]+b[1])/2),~~((a[2]+b[2])/2));}

生成随机十六进制颜色:

function rndHex(){return'#'+('00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6);}

运行演示代码片段:

// color functions (average/random/conversion)
function hexToRgb(h){return['0x'+h[1]+h[2]|0,'0x'+h[3]+h[4]|0,'0x'+h[5]+h[6]|0]}
function rgbToHex(r,g,b){return"#"+((1<<24)+(r<<16)+(g<<8)+ b).toString(16).slice(1);}
function rndHex(){return'#'+('00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6);}
function avgHex(h1,h2){a=hexToRgb(h1);b=hexToRgb(h2);return rgbToHex(~~((a[0]+b[0])/2),~~((a[1]+b[1])/2),~~((a[2]+b[2])/2));}

//code below is just for the demo
function auto(){if(chk.checked){tmr=setInterval(rnd,1000)}else{clearTimeout(tmr)}}auto();
function rnd(go){for(h of[h1,h2]){h.value=rndHex();}avgInput();}
addEventListener('input',avgInput); 
function avgInput(){ // get avg & colorize
 ha.value=avgHex(h1.value,h2.value);
 for(h of [h1,h2,ha])h.style.background=h.value;
}
*{font-family:monospace;font-size:5vw; }
<label>Color 1 → <input id='h1'></label><br>
<label>Average → <input id='ha'></label><br>
<label>Color 2 → <input id='h2'></label><br>
<label>Type hex colors or <input type='checkbox' id='chk' onclick='auto()' style=' transform: scale(1.5)'checked>Autorandom</label>