xxxxxxxxxx
function rgb(r, g, b){
// complete this function
return hexC(r)+hexC(g)+hexC(b)
}
function hexC(v){
if(v>255){
v=255
}else if(v<0){
v=0
}
let a=v%16;
let b=Math.floor(v/16);
return hmaps[b]+hmaps[a]
}
let hmaps={
0:'0',1:'1',2:'2',3:'3',4:'4',5:'5',6:'6',7:'7',8:'8',9:'9',10:'A',11:'B',12:'C',13:'D',14:'E',15:'F'
}
xxxxxxxxxx
function rgbToHex(r, g, b) {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
if(result){
var r= parseInt(result[1], 16);
var g= parseInt(result[2], 16);
var b= parseInt(result[3], 16);
return r+","+g+","+b;//return 23,14,45 -> reformat if needed
}
return null;
}
console.log(rgbToHex(10, 54, 120)); //#0a3678
console.log(hexToRgb("#0a3678"));//"10,54,120"
xxxxxxxxxx
// Convert RGB to Hex
function getColorFun(r, g, b) {
return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
getColorFun(178, 232, 55);
// The output here is #b2e837
xxxxxxxxxx
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;
}
var hex = "#0a3678";
console.log(hexToRgb(hex).r+","+hexToRgb(hex).g+","+hexToRgb(hex).b);//10,54,120
xxxxxxxxxx
const rgb2hex = (rgb) => `#${rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/).slice(1).map(n => parseInt(n, 10).toString(16).padStart(2, '0')).join('')}`
// Use as you wish...
console.log(rgb2hex('rgb(0,0,0)'))
console.log(rgb2hex('rgb(255, 255, 255)'))
console.log(rgb2hex('rgb(255,0,0)'))
console.log(rgb2hex('rgb(38, 170, 90)'))
Run code snippet
xxxxxxxxxx
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
Run code snippet
xxxxxxxxxx
function hexToRgb(hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
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";
alert(hexToRgb("#03f").g); // "51";
Run code snippet
xxxxxxxxxx
function rgba2hex(rgba) {
rgba = rgba.match(
/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i
);
return rgba && rgba.length === 4
? "#" +
("0" + parseInt(rgba[1], 10).toString(16)).slice(-2) +
("0" + parseInt(rgba[2], 10).toString(16)).slice(-2) +
("0" + parseInt(rgba[3], 10).toString(16)).slice(-2)
: "";
}
// examples
console.log(rgba2hex('rgba(240, 240, 240, 0.5)'));
console.log(rgba2hex('rgba(40, 20, 80, 1.0)'));