RGB to hex and hex to RGB

前端 未结 30 2820
遥遥无期
遥遥无期 2020-11-21 06:56

How to convert colors in RGB format to hex format and vice versa?

For example, convert \'#0080C0\' to (0, 128, 192).

30条回答
  •  逝去的感伤
    2020-11-21 07:02

    The top rated answer by Tim Down provides the best solution I can see for conversion to RGB. I like this solution for Hex conversion better though because it provides the most succinct bounds checking and zero padding for conversion to Hex.

    function RGBtoHex (red, green, blue) {
      red = Math.max(0, Math.min(~~this.red, 255));
      green = Math.max(0, Math.min(~~this.green, 255));
      blue = Math.max(0, Math.min(~~this.blue, 255));
    
      return '#' + ('00000' + (red << 16 | green << 8 | blue).toString(16)).slice(-6);
    };
    

    The use of left shift '<<' and or '|' operators make this a fun solution too.

提交回复
热议问题