Average 2 hex colors together in javascript

后端 未结 8 2010
天命终不由人
天命终不由人 2021-01-31 20:13

Alright thought I would throw this one out there for the crowd to think over.

Given a function (written in javascript) that expects two strings

8条回答
  •  醉梦人生
    2021-01-31 20:32

    Very late to this party, but I was personally looking for a way to average an undefined amount of HEX values. Based on the answer @RobG, I came up with this. Granted, the more colors you add the more brown/greyish they get, but, perhaps it helps!

    /**
     * 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"

提交回复
热议问题