Croximo Crox
Croximo Crox

Reputation: 89

Getting Hex from RGBA in js

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.

Upvotes: 0

Views: 3364

Answers (2)

Robin Delaporte
Robin Delaporte

Reputation: 585

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

Upvotes: 1

GMKHussain
GMKHussain

Reputation: 4719

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

Upvotes: 0

Related Questions