Created
August 6, 2016 09:34
-
-
Save binarymax/0c12f01056c1ab947216c7d49ba58d72 to your computer and use it in GitHub Desktop.
Use getComputedStyle to get an RGBA value from any supported CSS color.
This file contains hidden or 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
(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