Skip to content

Instantly share code, notes, and snippets.

@av01d
Last active February 9, 2024 16:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save av01d/8f068dd43447b475dec4aad0a6107288 to your computer and use it in GitHub Desktop.
Save av01d/8f068dd43447b475dec4aad0a6107288 to your computer and use it in GitHub Desktop.
Javascript: Convert any color (hex, hexa, rgb, rgba, hsl, named) to [r,g,b,a] array
/**
* Convert any color string to an [r,g,b,a] array.
* @author Arjan Haverkamp (arjan-at-avoid-dot-org)
* @param {string} color Any color. F.e.: 'red', '#f0f', '#ff00ff', 'rgb(x,y,x)', 'rgba(r,g,b,a)', 'hsl(180, 50%, 50%)'
* @returns {array} [r,g,b,a] array. Caution: returns [0,0,0,0] for invalid color.
*/
const colorValues = color => {
const div = document.createElement('div');
div.style.backgroundColor = color;
document.body.appendChild(div);
let rgba = getComputedStyle(div).getPropertyValue('background-color');
div.remove();
if (rgba.indexOf('rgba') === -1) {
rgba += ',1'; // convert 'rgb(R,G,B)' to 'rgb(R,G,B)A' which looks awful but will pass the regxep below
}
return rgba.match(/[\.\d]+/g).map(a => {
return +a
});
}
@av01d
Copy link
Author

av01d commented Aug 5, 2021

Example usage:

colorValues('transparent'); // [0,0,0,0]
colorValues('white'); // [255, 255, 255, 1]
colorValues('teal'); // [0, 128, 128, 1]
colorValues('rgba(11,22,33,.44)'); // [11, 22, 33, 0.44]
colorValues('rgb(11,22,33)'); // [11, 22, 33, 1]
colorValues('#abc'); // [170, 187, 204, 1]
colorValues('#abc6'); // [170, 187, 204, 0.4]
colorValues('#aabbcc'); // [170, 187, 204, 1]
colorValues('#aabbcc66'); // [170, 187, 204, 0.4]
colorValues('asdf'); // [0,0,0,0]
colorValues(''); // [0,0,0,0]
colorValues(NaN); // [0,0,0,0]
colorValues(123); // [0,0,0,0]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment