Skip to content

Instantly share code, notes, and snippets.

@carlosvega20
Last active November 16, 2016 20:28
Show Gist options
  • Save carlosvega20/9dd38315ed39741f534e to your computer and use it in GitHub Desktop.
Save carlosvega20/9dd38315ed39741f534e to your computer and use it in GitHub Desktop.
//StackOverflow:
//http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
//Solution 1.
//////////////////////////////////////////////
function rgbToHex(r, g, b) {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
//////////////////////////////////////////////
//Solution 2.
//////////////////////////////////////////////
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
alert( hexToRgb("#0033ff").g ); // "51";
//////////////////////////////////////////////
//Solution 3.
//////////////////////////////////////////////
function rgbToHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}
function toHex(n) {
n = parseInt(n,10);
if (isNaN(n)) return "00";
n = Math.max(0,Math.min(n,255));
return "0123456789ABCDEF".charAt((n-n%16)/16)
+ "0123456789ABCDEF".charAt(n%16);
}
///////////////////////////////////////////////
//solution 3.
//////////////////////////////////////////////
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function rgbToHex(r, g, b) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
alert( rgbToHex(0, 51, 255) ); // #0033ff
//////////////////////////////////////////////
//Solution 4. by Carlos
//Convert RGB Values in Hexadecimal color
//R:Number [0-255], G:Number [0-255], B:Number [0-255]
//return Hexagecimal String with the hash. ex: '#ff0000'
function rgb_to_hex (R, G, B){
//[0-9] 10 11 12 13 14 15
//[0-9] A B C D E F
function toLetters (arg){
return ['a', 'b', 'c', 'd', 'e', 'f'].find(function (el, i, arr) {
if (arg === i+10) return el
})
}
// 255 -> 15
// x -> ?
//? = x*15/255
R = Math.round((Math.abs(R)*15)/255);
R = (R>9) ? toLetters(R):R;
G = Math.round((Math.abs(G)*15)/255);
G = (G>9) ? toLetters(G):G;
B = Math.round((Math.abs(B)*15)/255);
B = (B>9) ? toLetters(B):B;
return '#'+R+R+G+G+B+B;
}
alert.log(rgb_to_hex(255,255,20));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment