css 如何使用javascript将RGBA转换为十六进制颜色代码

emeijp43  于 2023-04-08  发布在  Java
关注(0)|答案(8)|浏览(330)

我试图将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)

这里我需要阿尔法值也转换为十六进制代码。
请建议如何转换

输出

预计:000000bd

8ftvxx2r

8ftvxx2r1#

由于rgba()表示法中的Alpha通道表示为0 ~ 1值,因此在尝试将其转换为十六进制形式之前,需要将其乘以255:

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表示法,因此您可能更喜欢使用其他方法来转换值,具体取决于您想要使用它做什么。

kcwpcxri

kcwpcxri2#

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

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;
};
qf9go6mv

qf9go6mv3#

太棒了@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;
}
0h4hbjxa

0h4hbjxa4#

试试这个:

  • ✓支持alpha rgba(255, 255, 255, 0) => #ffffff00
  • 适用于单个数字rgba(0, 0, 0, 0) => #00000000
  • ✓与RGB以及工作rgba(124, 255, 3) => #7cff03
  • ✓您可以将alpha通道切掉rgba(255, 255, 255, 0) => #ffffff
function RGBAToHexA(rgba, forceRemoveAlpha = false) {
  return "#" + rgba.replace(/^rgba?\(|\s+|\)$/g, '') // Get's rgba / rgb string values
    .split(',') // splits them at ","
    .filter((string, index) => !forceRemoveAlpha || index !== 3)
    .map(string => parseFloat(string)) // Converts them to numbers
    .map((number, index) => index === 3 ? Math.round(number * 255) : number) // Converts alpha to 255 number
    .map(number => number.toString(16)) // Converts numbers to hex
    .map(string => string.length === 1 ? "0" + string : string) // Adds 0 when length of one number is 1
    .join("") // Puts the array to togehter to a string
}

//
// Only tests below! Click "Run code snippet" to see results
//

// RGBA with Alpha value
expect(RGBAToHexA("rgba(255, 255, 255, 0)"), "#ffffff00")
expect(RGBAToHexA("rgba(0, 0, 0, 0)"), "#00000000")
expect(RGBAToHexA("rgba(124, 255, 3, 0.5)"), "#7cff0380")
expect(RGBAToHexA("rgba(124, 255, 3, 1)"), "#7cff03ff")

// RGB value 
expect(RGBAToHexA("rgba(255, 255, 255)"), "#ffffff")
expect(RGBAToHexA("rgba(0, 0, 0)"), "#000000")
expect(RGBAToHexA("rgba(124, 255, 3)"), "#7cff03")

// RGBA without Alpha value
expect(RGBAToHexA("rgba(255, 255, 255, 0)", true), "#ffffff")
expect(RGBAToHexA("rgba(0, 0, 0, 0)", true), "#000000")
expect(RGBAToHexA("rgba(124, 255, 3, 0.5)", true), "#7cff03")
expect(RGBAToHexA("rgba(124, 255, 3, 1)", true), "#7cff03")

function expect(result, expectation) {
  console.log(result === expectation ? "✓" : "X", result, expectation)
}

代码构建基于:

fhg3lkii

fhg3lkii5#

如果你有字符串形式的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
oxcyiej7

oxcyiej76#

只需创建一个功能,以更有效!代码与上面相同。

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)'))
lqfhib0f

lqfhib0f7#

这是一个简化的选项。

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。

gwbalxhn

gwbalxhn8#

function rgbaToHex(r, g, b, a) {
  const red = r.toString(16).padStart(2, '0');
  const green = g.toString(16).padStart(2, '0');
  const blue = b.toString(16).padStart(2, '0');
  const alpha = Math.round(a * 255).toString(16).padStart(2, '0');
  return `#${red}${green}${blue}${alpha}`;
}

console.log(rgbaToHex(2,2,2,0.6));
console.log(rgbaToHex(2,2,2,0.50));

相关问题