Average 2 hex colors together in javascript

后端 未结 8 2016
天命终不由人
天命终不由人 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:24

    Here is the function

    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"
    

    To check you can use this link and midpoint 1 then blend https://meyerweb.com/eric/tools/color-blend/#CC0D73:0000FF:1:hex

提交回复
热议问题