Thursday, May 11, 2017

Convert RGB(A) output to Hex Color

Update from my Convert jQuery RGB output to Hex Color Post Modern browsers will soon support four and eight-digit hex colors, which means you now include an alpha channel with your color. As you can see in the comments of this CSS Tricks post, the alpha channel conversion is different from the other color channels and this makes it very confusing to convert:
  • The r (red), g (green), and b (blue) channels have decimal values ranging from 0 to 255.
  • the a (alpha) channel has a decimal value that ranges from 0 to 100.
My old post Convert jQuery RGB output to Hex Color was written to ignore the alpha channel when entering an RGBA value. This post updates both the javascript and the demo to output an #RRGGBB or #RRGGBBAA hex code value.

function rgb2hex(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 !== "") {
    isPercent = alpha.indexOf("%") > -1;
    a = parseFloat(alpha);
    if (!isPercent && a >= 0 && a <= 1) {
      a = Math.round(255 * a);
    } else if (isPercent && a >= 0 && a <= 100) {
      a = Math.round(255 * a / 100)
    } else {
      a = "";
    }
  }
  if (a) {
    hex += (a | 1 << 8).toString(16).slice(1);
  }
  return hex;
}
I've copied some of the above code from the rgb-hex node module, where I also contributed alpha channel support.

No comments:

Post a Comment