RGB to hex and hex to RGB

前端 未结 30 2775
遥遥无期
遥遥无期 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:28

    Here's my version:

    function rgb_to_hex(red, green, blue) {
      const rgb = (red << 16) | (green << 8) | (blue << 0);
      return '#' + (0x1000000 + rgb).toString(16).slice(1);
    }
    
    function hex_to_rgb(hex) {
      const normal = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
      if (normal) return normal.slice(1).map(e => parseInt(e, 16));
      const shorthand = hex.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
      if (shorthand) return shorthand.slice(1).map(e => 0x11 * parseInt(e, 16));
      return null;
    }
    

提交回复
热议问题