Skip to content

Instantly share code, notes, and snippets.

@binarymax
Created August 6, 2016 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save binarymax/0c12f01056c1ab947216c7d49ba58d72 to your computer and use it in GitHub Desktop.
Save binarymax/0c12f01056c1ab947216c7d49ba58d72 to your computer and use it in GitHub Desktop.
Use getComputedStyle to get an RGBA value from any supported CSS color.
(function(){
var getColor = function(c) {
var temp = document.createElement("div");
var color = {r:0,g:0,b:0,a:0};
temp.style.color = c;
temp.style.display = "none";
document.body.appendChild(temp);
var style = window.getComputedStyle(temp,null).color;
document.body.removeChild(temp);
var recol = /([\.\d]+)/g;
var vals = style.match(recol);
if (vals.length>2) {
color.r = parseInt(vals[0])||0;
color.g = parseInt(vals[1])||0;
color.b = parseInt(vals[2])||0;
color.a = Math.round((parseFloat(vals[3])||1.0)*255);
}
return color;
}
console.log(getColor("blue"));
console.log(getColor("rgba(0,0,255,0.5)"));
console.log(getColor("rgb(0,0,255)"));
console.log(getColor("#0000ff"));
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment