【问题标题】:How to convert RGBA to Hex color code using javascript如何使用 javascript 将 RGBA 转换为十六进制颜色代码
【发布时间】:2018-10-03 02:09:07
【问题描述】:

我尝试将rgba 转换为十六进制颜色代码,但无法隐藏我能够转换的剩余颜色的不透明度值,

下面是我的代码

var colorcode = "rgba(0, 0, 0, 0.74)";

var finalCode = rgba2hex(colorcode)

function rgba2hex(orig) {
    var a, isPercent,
    rgb = orig.replace(/\s/g, '').match(/^rgba?\((\d+),(\d+),(\d+),?([^,\s)]+)?/i),
    alpha = (rgb && rgb[4] || "").trim(),
    hex = rgb ?
    (rgb[1] | 1 << 8).toString(16).slice(1) +
    (rgb[2] | 1 << 8).toString(16).slice(1) +
    (rgb[3] | 1 << 8).toString(16).slice(1) : orig;
  
    if (alpha !== "") { a = alpha; }
    else { a = 01; }
    hex = hex + a;
  
    return hex;
}

console.log(finalCode)

这里我需要 alpha 值也转换为十六进制代码。

请建议如何转换

输出

期望:000000bd

【问题讨论】:

标签: javascript css


【解决方案1】:

由于 rgba() 表示法中的 alpha 通道表示为 0 ~ 1 值,因此您需要先将其乘以 255,然后再尝试将其转换为 HEX 形式:

var colorcode = "rgba(0, 0, 0, 0.74)";

var finalCode = rgba2hex(colorcode)

function rgba2hex(orig) {
  var a, isPercent,
    rgb = orig.replace(/\s/g, '').match(/^rgba?\((\d+),(\d+),(\d+),?([^,\s)]+)?/i),
    alpha = (rgb && rgb[4] || "").trim(),
    hex = rgb ?
    (rgb[1] | 1 << 8).toString(16).slice(1) +
    (rgb[2] | 1 << 8).toString(16).slice(1) +
    (rgb[3] | 1 << 8).toString(16).slice(1) : orig;

  if (alpha !== "") {
    a = alpha;
  } else {
    a = 01;
  }
  // multiply before convert to HEX
  a = ((a * 255) | 1 << 8).toString(16).slice(1)
  hex = hex + a;

  return hex;
}

function test(colorcode) {
  console.log(colorcode, rgba2hex(colorcode));
}

test("rgba(0, 0, 0, 0.74)");
test("rgba(0, 0, 0, 1)");
test("rgba(0, 0, 0, 0)");
test("rgba(0, 255, 0, 0.5)");

但请注意,这只是 rgba 表示法之一,例如,基于百分比的表示法会失败。
另请注意,所有浏览器都不支持 RGBA HEX 表示法,因此您可能更喜欢使用其他方法来转换您的值,具体取决于您想用它做什么。

【讨论】:

    【解决方案2】:

    很棒的@kaiido,我试过这种方式

    function rgba2hex(orig) {
          var a, isPercent,
            rgb = orig.replace(/\s/g, '').match(/^rgba?\((\d+),(\d+),(\d+),?([^,\s)]+)?/i),
            alpha = (rgb && rgb[4] || "").trim(),
            hex = rgb ? 
            (rgb[1] | 1 << 8).toString(16).slice(1) +
            (rgb[2] | 1 << 8).toString(16).slice(1) +
            (rgb[3] | 1 << 8).toString(16).slice(1) : orig;
              if (alpha !== "") {
                a = alpha;
              } else {
                a = 01;
              }
    
              a = Math.round(a * 100) / 100;
                var alpha = Math.round(a * 255);
                var hexAlpha = (alpha + 0x10000).toString(16).substr(-2).toUpperCase();
                hex = hex + hexAlpha;
    
          return hex;
    }
    

    【讨论】:

      【解决方案3】:

      如果你有 rgba 颜色作为字符串,你可以这样做。

      const color = 'rgba(249,6,6,1,0)';
      const rgba = color.replace(/^rgba?\(|\s+|\)$/g, '').split(',');
      
      const hex = `#${((1 << 24) + (parseInt(rgba[0]) << 16) + (parseInt(rgba[1]) << 8) + parseInt(rgba[2])).toString(16).slice(1)}`;
      console.log(hex); // #f90606
      

      【讨论】:

      • 这不适合 alpha 通道
      【解决方案4】:

      只需创建一个功能更有效!代码同上。

          var color;
      
          function HexCode(color){
              const rgba = color.replace(/^rgba?\(|\s+|\)$/g, '').split(',');
              const hex = `#${((1 << 24) + (parseInt(rgba[0]) << 16) + (parseInt(rgba[1]) << 8) + parseInt(rgba[2])).toString(16).slice(1)}`;
              
              return hex;
          }
      
          console.log(HexCode('rgba(0,255,255,0.1)'))
      

      【讨论】:

      • 刚刚测试了你的函数,它不适合 alpha 通道。
      【解决方案5】:

      我的解决方案。希望有用。

      const rgbaToHex = (color: string): string => {
        if (/^rgb/.test(color)) {
          const rgba = color.replace(/^rgba?\(|\s+|\)$/g, '').split(',');
      
          // rgb to hex
          // eslint-disable-next-line no-bitwise
          let hex = `#${((1 << 24) + (parseInt(rgba[0], 10) << 16) + (parseInt(rgba[1], 10) << 8) + parseInt(rgba[2], 10))
            .toString(16)
            .slice(1)}`;
      
          // added alpha param if exists
          if (rgba[4]) {
            const alpha = Math.round(0o1 * 255);
            const hexAlpha = (alpha + 0x10000).toString(16).substr(-2).toUpperCase();
            hex += hexAlpha;
          }
      
          return hex;
        }
        return color;
      };
      

      【讨论】:

      • 欢迎来到 Stack Overflow。没有任何解释的代码很少有帮助。 Stack Overflow 是关于学习的,而不是提供 sn-ps 来盲目复制和粘贴。请编辑您的问题并解释它如何回答所提出的具体问题。见How to Answer
      【解决方案6】:

      这是一个简化的选项。

      function rgbToHex(rgb) {
        return '#' + rgb.match(/[0-9|.]+/g).map((x,i) => i === 3 ? parseInt(255 * parseFloat(x)).toString(16) : parseInt(x).toString(16)).join('')
      }
      

      适用于 rgb 和 rgba。

      【讨论】:

      • 这几乎就在那里,但它不会用0 填充单个数字。在这种情况下,检查字符串长度的一个简单问题是 1 并在前面加上 0。
      猜你喜欢
      • 2012-05-14
      • 2018-04-08
      • 2015-05-19
      • 2017-06-13
      • 2018-07-10
      • 2020-10-03
      • 2021-02-12
      • 2019-10-11
      相关资源
      最近更新 更多