Skip to content

Instantly share code, notes, and snippets.

@sorensen
Created March 20, 2012 17:20
Show Gist options
  • Save sorensen/2138335 to your computer and use it in GitHub Desktop.
Save sorensen/2138335 to your computer and use it in GitHub Desktop.
Hex / RGB translation helpers
// http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
hexToRgb = (function() {
var cache = {}
return function(hex) {
if (cache[hex]) return cache[hex]
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
return result ? cache[hex] = {
r: parseInt(result[1], 16)
, g: parseInt(result[2], 16)
, b: parseInt(result[3], 16)
} : null
}
})()
var hexToRgba = (function() {
var cache = {}
return function(hex, alpha) {
if (cache[hex]) return cache[hex]
var rgb = hexToRgb(hex)
return 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + alpha + ')'
}
})()
var rgbToHex = function(r, g, b) {
return "#" + (
(1 << 24)
+ (r << 16)
+ (g << 8) + b
).toString(16).slice(1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment