Last active
February 9, 2024 16:01
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: