Подтвердить что ты не робот

Среднее количество цветов в два гектара в javascript

Хорошо, я подумал, что я брошу это там, чтобы толпа подумала.

Учитывая функцию (написанную в javascript), которая ожидает, что две строки будут сформированы как шестнадцатеричный цвет (ex # FF0000)

возвращает шестнадцатеричный цвет, который является средним для обоих пройденных цветов.

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

--edit--

средний будет определяться как enter image description here

, если пройденный цвет был желтым, а второй светло-фиолетовым, возвращаемый цвет был бы оранжево-оранжевым.

4b9b3361

Ответ 2

Требуется только несколько строк 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('');
  }
}());

Ответ 3

Мне нравится домашнее задание, но вот моя подсказка.

Возьмите каждое шестнадцатеричное значение для R, G и B и сравните каждую из них. При необходимости перейдите в десятичный, чтобы выполнить математику.

Функция d2h (d) {return d.toString(16).padStart(2, '0');}

функция h2d (h) {return parseInt (h, 16);}

Затем верните строку, содержащую конкатенированные значения трех элементов.

Ответ 4

Для любого (скорее всего, моего будущего), ищущего быстрый/грязный/удобный /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));

Ответ 5

Вот моя функция, надеюсь, что это поможет.

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);}}

Ответ 6

Вот функция

function avgColor(color1, color2) {
  //separate each color alone (red, green, blue) from the first parameter (color1) 
  //then convert to decimal
  let color1Decimal = {
    red: parseInt(color1.slice(0, 2), 16),
    green: parseInt(color1.slice(2, 4), 16),
    blue: parseInt(color1.slice(4, 6), 16)
  }
  //separate each color alone (red, green, blue) from the second parameter (color2) 
  //then convert to decimal
  let color2Decimal = {
    red: parseInt(color2.slice(0, 2), 16),
    green: parseInt(color2.slice(2, 4), 16),
    blue: parseInt(color2.slice(4, 6), 16),
  }
  // calculate the average of each color (red, green, blue) from each parameter (color1,color2) 
  let color3Decimal = {
    red: Math.ceil((color1Decimal.red + color2Decimal.red) / 2),
    green: Math.ceil((color1Decimal.green + color2Decimal.green) / 2),
    blue: Math.ceil((color1Decimal.blue + color2Decimal.blue) / 2)
  }
  //convert the result to hexadecimal and don't forget if the result is one character
  //then convert it to uppercase
  let color3Hex = {
    red: color3Decimal.red.toString(16).padStart(2, '0').toUpperCase(),
    green: color3Decimal.green.toString(16).padStart(2, '0').toUpperCase(),
    blue: color3Decimal.blue.toString(16).padStart(2, '0').toUpperCase()
  }
  //put the colors (red, green, blue) together to have the output
  let color3 = color3Hex.red + color3Hex.green + color3Hex.blue
  return color3
}
console.log(avgColor("FF33CC", "3300FF"))
// avgColor("FF33CC", "3300FF") => "991AE6"

console.log(avgColor("991AE6", "FF0000"))
// avgColor("991AE6", "FF0000") => "CC0D73"

console.log(avgColor("CC0D73", "0000FF"))
// avgColor("CC0D73", "0000FF") => "6607B9"

Для проверки вы можете использовать эту ссылку и середину 1, а затем смешатьhttps://meyerweb.com/eric/tools/color-blend/#CC0D73:0000FF:1:hex