RGB 转 Hex 和 Hex 转 RGB

hex转rgb颜色

const hexToRgb = hex => {
     
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result
    ? {
     
        r: parseInt(result[1], 16).toString(),
        g: parseInt(result[2], 16).toString(),
        b: parseInt(result[3], 16).toString(),
      }
    : null;
};
alert(hexToRgb("#0033ff").g); // "51";

rgb 转 hex

function rgbToHex(r, g, b) {
     
  return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}

alert(rgbToHex(0, 51, 255)); // #0033ff

参考:
stack overflow RGB to Hex and Hex to RGB
实时查看颜色

你可能感兴趣的:(javascript,颜色转换)