Last active
January 24, 2018 14:32
-
-
Save Rycochet/8597336 to your computer and use it in GitHub Desktop.
Javascript hex to rgb()/rgba()
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
// Please note this uses my Math.range and String.regex methods | |
/** | |
* Convert a hex colour to a rgb/rgba value | |
* @param {string} hex | |
* @param {?number} opacity | |
* @returns {string} | |
*/ | |
function rgba(hex, opacity) { | |
var colours = hex.regex(/#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})/i).map(function(val) { | |
return Math.range(0, parseInt(val, 16), 255); | |
}).join(","); | |
if (opacity === undefined) { | |
return "rgb(" + colours + ")"; | |
} | |
return "rgba(" + colours + "," + opacity + ")"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Where does the
range
method come from? I can't find it in the documents forMath