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



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

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

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

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

试试这个:

  • ✓ 适用于阿尔法rgba(255, 255, 255, 0) => #ffffff00
  • ✓ 适用于个位数rgba(0, 0, 0, 0) => #00000000
  • ✓ 也适用于 RGB rgb(124, 255, 3) => #7cff03
  • ✓您可以切掉阿尔法通道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)
}

代码基于以下各项构建:

  • https://css-tricks.com/converting-color-spaces-in-javascript/

太@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;
}

如果你有 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

只需创建一个更有效的函数!代码与上面相同。

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

这是一个简化的选项。

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。

  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));

相关内容

最新更新