hex-rgb.js

  1. /**
  2. * @func hex2rgb
  3. * @desc Return an RGBA color from a Hex color.
  4. * @param {StringHex} hex
  5. * @return {ArrayRGBA}
  6. * @example
  7. * hex2rgb("#f00") // => [100, 0, 0, 100]
  8. * hex2rgb("#f00f") // => [100, 0, 0, 100]
  9. * @example
  10. * hex2rgb("#ff0000") // => [100, 0, 0, 100]
  11. * hex2rgb("#ff0000ff") // => [100, 0, 0, 100]
  12. */
  13. export function hex2rgb(hex) {
  14. // #<hex-color>{3,4,6,8}
  15. const [, r, g, b, a, rr, gg, bb, aa] = hex.match(hexColorMatch) || [];
  16. if (rr !== undefined || r !== undefined) {
  17. const red = rr !== undefined ? parseInt(rr, 16) : parseInt(r + r, 16);
  18. const green = gg !== undefined ? parseInt(gg, 16) : parseInt(g + g, 16);
  19. const blue = bb !== undefined ? parseInt(bb, 16) : parseInt(b + b, 16);
  20. const alpha = aa !== undefined ? parseInt(aa, 16) : a !== undefined ? parseInt(a + a, 16) : 255;
  21. return [red, green, blue, alpha].map(c => c * 100 / 255);
  22. }
  23. return undefined;
  24. }
  25. /**
  26. * @func rgb2hex
  27. * @desc Return a HEX color from an RGB color
  28. * @param {Number} r - Red (0 - 100)
  29. * @param {Number} g - Green (0 - 100)
  30. * @param {Number} b - Blue (0 - 100)
  31. * @return {StringHex}
  32. * @example
  33. * rgb2hex(100, 0, 0) // => "#ff0000"
  34. */
  35. export function rgb2hex(rgbR, rgbG, rgbB) {
  36. return `#${((1 << 24) + (Math.round(rgbR * 255 / 100) << 16) + (Math.round(rgbG * 255 / 100) << 8) + Math.round(rgbB * 255 / 100)).toString(16).slice(1)}`;
  37. }
  38. const hexColorMatch = /^#?(?:([a-f0-9])([a-f0-9])([a-f0-9])([a-f0-9])?|([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})?)$/i;