0

How to convert given RGBA to hex assuming value of each of them are given as separate variables r, g, b, a where r, g & b are 1-225 and a in 0-1 in javascript.

Please define a function for it.

Croximo Crox
  • 79
  • 10
  • Does this answer your question? [How to convert RGBA to Hex color code using javascript](https://stackoverflow.com/questions/49974145/how-to-convert-rgba-to-hex-color-code-using-javascript) – Modus Tollens Jul 01 '20 at 12:17

2 Answers2

1

If you don't need the "a" from rgbA, tell me, I will remove its support.

But basically, you just convert every integer to hex string and add 0 if needed.

function rgbaToHex (r,g,b,a) {
  var outParts = [
    r.toString(16),
    g.toString(16),
    b.toString(16),
    Math.round(a * 255).toString(16).substring(0, 2)
  ];

  // Pad single-digit output values
  outParts.forEach(function (part, i) {
    if (part.length === 1) {
      outParts[i] = '0' + part;
    }
  })

  return ('#' + outParts.join(''));
}

alert(rgbaToHex(255,34,56,1));
Robin Delaporte
  • 575
  • 5
  • 15
0

RGB to hex conversion

function HexFunc(c) {
  var hex = c.toString(16);
  return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHexFunc(r, g, b) {
  let v = "#" + HexFunc(r) + HexFunc(g) + HexFunc(b);
  console.log(v);
  return v;
}

alert(rgbToHexFunc(092, 334, 159)); // #5c94e9f
GMKHussain
  • 3,342
  • 1
  • 21
  • 19