Last active
December 17, 2015 16:29
-
-
Save fitnr/5639447 to your computer and use it in GitHub Desktop.
convert hex to rgb
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
// Adapted from http://www.javascripter.net/faq/hextorgb.htm | |
function hexer(h, from, to) { return parseInt((h.charAt(0)=="#" ? h.substring(1,7):h).substring(from,to), 16); } | |
function hexToR(h) {return hexer(h, 0, 2);} | |
function hexToG(h) {return hexer(h, 2, 4);} | |
function hexToB(h) {return hexer(h, 4, 6);} | |
function rnd(x) {return Math.round(100*x) / 100;} | |
function hexToIntRGB(h) { return [hexToR(h), hexToG(h), hexToB(h)]; } | |
function hexToDecRGB(h) { return [rnd(hexToR(h)/256), rnd(hexToG(h)/256), rnd(hexToB(h)/256)]; } | |
function decRGBToIntRGB(rgb) { return rgb.map(function(r) { return parseInt(r * 256);}); } | |
function intRGBToDecRGB(rgb) { return rgb.map(function(r) { return r / 256;}); } | |
/* example use */ | |
// e.g., copied from http://bl.ocks.org/mbostock/5577023 | |
var colors = ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628"]; | |
for (var i = colors.length - 1; i >= 0; i--) { | |
console.log(hexToDecRGB(colors[i])); | |
} | |
/* returns: | |
[0.65, 0.34, 0.16] | |
[1, 1, 0.2] | |
[1, 0.5, 0] | |
[0.59, 0.3, 0.64] | |
[0.3, 0.68, 0.29] | |
[0.21, 0.49, 0.72] | |
[0.89, 0.1, 0.11] | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment