js rgb转hex

    colorRgbToHex(rgb) {
                let res = rgb.toString().split(',')
                let r = res[0]
                let g = res[1]
                let b = res[2]
                let _rgb = 'rgb(' + r + ',' + g +','+ b + ')'
                return this.rgbToHex(_rgb);
            },
            rgbToHex(rgb) {
                var bg = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

                function hex(x) {
                    return ("0" + parseInt(x).toString(16)).slice(-2);
                }
                return ("#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3])).toUpperCase();
            }

console.log(this.rgbToHex('rgb(204,0,255)'));


            {{rgb}}
        

hex转rgb

function hexToRgb (hex) {
  var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  hex = hex.replace(shorthandRegex, function (m, r, g, b) {
    return r + r + g + g + b + b;
  });

  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? 'rgb(' + [
    parseInt(result[1], 16),
    parseInt(result[2], 16),
    parseInt(result[3], 16)
  ].join(',') + ')' : hex;
}
 
console.log(hexToRgb('#C0F'));    // Output: rgb(204,0,255)
console.log(hexToRgb('#CC00FF')); // Output: rgb(204,0,255)

hex 转rgba

function hexToRgba (hex, opacity) {
  var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  hex = hex.replace(shorthandRegex, function (m, r, g, b) {
    return r + r + g + g + b + b;
  });

  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  opacity = opacity >= 0 && opacity <= 1 ? Number(opacity) : 1;
  return result ? 'rgba(' + [
    parseInt(result[1], 16),
    parseInt(result[2], 16),
    parseInt(result[3], 16),
    opacity
  ].join(',') + ')' : hex;
}
 
console.log(hexToRgba('#C0F'));         // Output: rgb(204,0,255,1)
console.log(hexToRgba('#CC00FF', 0.3)); // Output: rgb(204,0,255,0.3)

rgb 转hex

function rgbToHex (rgb) {
  var bg = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
  function hex (x) {
    return ("0" + parseInt(x).toString(16)).slice(-2);
  }
  return ("#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3])).toUpperCase();
}
 
console.log(rgbToHex('rgb(204,0,255)')); // Output: #CC00FF

rgba 转hex

function rgbaToHex(rgba) {
  var bg = rgba.match(/^rgb\((\d+),\s*(\d+),\s*(\d+),\s*(\d?(\d|(\.[1-9]{1,2})))\)$/);
  function hex(x) {
    return ("0" + parseInt(x).toString(16)).slice(-2);
  }
  return ("#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3])).toUpperCase();
}
 
console.log(rgbaToHex('rgb(204,0,255,1)'));   // Output: #CC00FF
console.log(rgbaToHex('rgb(204,0,255,0.1)')); // Output: #CC00FF

你可能感兴趣的:(js rgb转hex)