RGB to hex and hex to RGB

前端 未结 30 2871
遥遥无期
遥遥无期 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条回答
  •  猫巷女王i
    2020-11-21 07:02

    For 3 digits hexToRgb function of Tim Down can be improved as below:

    var hex2Rgb = function(hex){
      var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})|([a-f\d]{1})([a-f\d]{1})([a-f\d]{1})$/i.exec(hex);
      return result ? {        
        r: parseInt(hex.length <= 4 ? result[4]+result[4] : result[1], 16),
        g: parseInt(hex.length <= 4 ? result[5]+result[5] : result[2], 16),
        b: parseInt(hex.length <= 4 ? result[6]+result[6] : result[3], 16),
        toString: function() {
          var arr = [];
          arr.push(this.r);
          arr.push(this.g);
          arr.push(this.b);
          return "rgb(" + arr.join(",") + ")";
        }
      } : null;
    };
    

提交回复
热议问题