Quick actions

cmd+k|ctrl+k

Navigation

Languages

color utility functions

Snippet info

Language

JavaScript

Visibility

public

Author

paulkotov

Created

2023-02-22T14:02:35.813874Z

Updated

2023-03-14T11:55:37.915778Z

function rgba2hex(r = 0, g = 0, b = 0, alpha) {
  let rgb =
    (r | (1 << 8)).toString(16).slice(1) + (g | (1 << 8)).toString(16).slice(1) + (b | (1 << 8)).toString(16).slice(1);

  if (alpha) {
    const a = ((alpha * 255) | (1 << 8)).toString(16).slice(1);
    rgb += a;
  }

  return rgb;
}

console.log(rgba2hex());
console.log(rgba2hex(0, 255, 0));
console.log(rgba2hex(0, 255, 0, 0.5));

function hex2rgba(color) {
  const r = parseInt(color.slice(1, 3), 16);
  const g = parseInt(color.slice(3, 5), 16);
  const b = parseInt(color.slice(5, 7), 16);
  let alpha = color.slice(7, 9) || 'ff';
  return `${r}${g}${b}${parseInt(alpha, 16)}`;
}

console.log(hex2rgba('#00ff007f'));
INFO