Created
August 8, 2010 03:10
-
-
Save shazow/513526 to your computer and use it in GitHub Desktop.
Helpers for manipulating colors in javascript.
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
/* Helpers for manipulating colors in javascript. */ | |
/* IE patch. :( */ | |
if(typeof String.prototype.trim !== 'function') { | |
String.prototype.trim = function() { | |
return this.replace(/^\s+|\s+$/g, ''); | |
} | |
} | |
/***/ | |
function assure_hash_prefix(s) { | |
if(s[0] == '#' || !(/^[\dabcdef]{3,6}$/).test(s)) return s; | |
return '#' + s; | |
} | |
function hex_to_rgb(hex) { | |
/* "FFFFFF" -> [255,255,255] */ | |
if(hex[0] == '#') { | |
hex = hex.substring(1,7); | |
} | |
return [parseInt(hex.substring (0, 2), 16), parseInt(hex.substring(2, 4), 16), parseInt(hex.substring(4, 6), 16)] | |
} | |
function rgb_to_hex(rgb) { | |
/* [255,255,255] -> "FFFFFF" */ | |
var r = (rgb[2] | (rgb[1] << 8) | (rgb[0] << 16)).toString(16); | |
// Pad 0's | |
for(var i=0, stop=6-r.length; i<stop; i++) r += "0"; | |
return r; | |
} | |
function css_to_rgb(s) { | |
/* "rgb(255, 255, 255)" or "#ffffff" -> [255,255,255] */ | |
if(s[0] == '#') return hex_to_rgb(s); // NOTE: IE8 does not always return rgb | |
return $.map(s.substring(4,s.length-1).split(','), function(o) { return parseInt(o.trim()) }); | |
} | |
function rgb_to_css(rgb) { | |
/* [255,255,255] -> "rgb(255, 255, 255)" */ | |
return 'rgb(' + rgb[0] + ',' + rgb[1] +',' + rgb[2] + ')'; | |
} | |
function rgb_to_hsv(rgb){ | |
/* [50,50,100] -> [170, 127.5, 100] */ | |
var r = rgb[0]/255, g = rgb[1]/255, b = rgb[2]/255; | |
var max = Math.max(r,g,b), min = Math.min(r,g,b); | |
if(max==min) return [0,0,max*255]; | |
var v = max, s = (max-min) / max; | |
var rc = (max-r) / (max-min), | |
gc = (max-g) / (max-min), | |
bc = (max-b) / (max-min); | |
if(r==max) h = bc-gc; | |
else if(g==max) h = 2+rc-bc; | |
else h = 4.0+gc-rc; | |
h = (h/6.0) % 1.0; | |
if(h<0) h += 1.0 | |
return [h*255,s*255,v*255]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment