hex与rgb(a)互相转换

hex与rgb都能代表颜色,使用效果上一样的,但有时需要做一些计算时就需要转化,特别是hex转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)

【国内直连ChatGPT 29元起】
国内直连ChatGPT,Plus会员每月29元起,支持最新o1模型探索更多领域,无需注册OpenAI账号。

hex转rgba

其实hex没有包含alpha通道,所以可以通过传入参数来实现

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

由于hex没有alpha通道,所以其实是放弃alpha通道,只能用rgb转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
分享

TITLE: hex与rgb(a)互相转换

LINK: https://www.qttc.net/477-hex-rgba.html

NOTE: 原创内容,转载请注明出自琼台博客