Skip to content

Instantly share code, notes, and snippets.

@lyatziv
Created July 14, 2022 17:01
Show Gist options
  • Save lyatziv/df7350d85ef36cc3d9358911072dc58e to your computer and use it in GitHub Desktop.
Save lyatziv/df7350d85ef36cc3d9358911072dc58e to your computer and use it in GitHub Desktop.
Get an array of rgb values for a color
// Requires window
const parseColor = (input) => {
var div = document.createElement('div');
document.body.appendChild(div)
div.style.color = input;
const style = window.getComputedStyle(div);
const ret = style.color.match(/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i);
document.body.removeChild(div);
if(ret) {
return [ret[1],ret[2],ret[3]];
} else {
throw new Error(`Error: ${input} could not be parsed.`);
}
}
console.log(parseColor('rgb(154,22,10)')) // ['154', '22', '10']
console.log(parseColor('#F4C005')) // ['244', '192', '5']
console.log(parseColor('tangerine')) // ['27', '27', '27']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment