Created
December 3, 2012 02:53
-
-
Save nornagon/4192305 to your computer and use it in GitHub Desktop.
Parse CSS colors like 'hsla(32,50%,20%,0.4)' into RGB components
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
// Tested in Chrome 23, Firefox 16, and IE9 in standards mode (i.e. with <!DOCTYPE html>). | |
// Converts '#f00', 'red', 'hsl(0, 100%, 50%)' and 'rgb(255,0,0)' to {r:255,g:0,b:0}. | |
function cssColorToRGB(cssColor) { | |
var s = document.createElement('span') | |
document.body.appendChild(s) | |
s.style.backgroundColor = cssColor | |
var rgb = getComputedStyle(s).backgroundColor | |
document.body.removeChild(s) | |
var m = /^rgb\((\d+), (\d+), (\d+)\)$/.exec(rgb) | |
if (!m) m = /^rgba\((\d+), (\d+), (\d+), ([\d.]+)\)$/.exec(rgb) | |
var r = parseInt(m[1]), g = parseInt(m[2]), b = parseInt(m[3]) | |
if (m[4]) | |
return {r:r, g:g, b:b, a:parseFloat(m[4])} | |
return {r:r, g:g, b:b} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment