online hexadecimal google convert conversión color javascript colors hex rgb

javascript - hexadecimal - rgb to hex google



RGB a Hex y Hex a RGB (30)

¿Cómo convertir colores en formato RGB a formato hexadecimal y viceversa?

Por ejemplo, convierta ''#0080C0'' a (0, 128, 192) .


ECMAScript versión 6 de la respuesta de Tim Down

Convertir RGB a hexadecimal

const rgbToHex = (r, g, b) => ''#'' + [r, g, b].map(x => { const hex = x.toString(16) return hex.length === 1 ? ''0'' + hex : hex }).join('''') console.log(rgbToHex(0, 51, 255)); // ''#0033ff''

Convertir hexadecimal a RGB

Devuelve una matriz [r, g, b] . Funciona también con tripletes hexadecimales de taquigrafía como "#03F" .

const hexToRgb = hex => hex.replace(/^#?([a-f/d])([a-f/d])([a-f/d])$/i ,(m, r, g, b) => ''#'' + r + r + g + g + b + b) .substring(1).match(/.{2}/g) .map(x => parseInt(x, 16)) console.log(hexToRgb("#0033ff")) // [0, 51, 255] console.log(hexToRgb("#03f")) // [0, 51, 255]

Bonificación: RGB a hexadecimal usando el método padStart()

const rgbToHex = (r, g, b) => ''#'' + [r, g, b] .map(x => x.toString(16).padStart(2, ''0'')).join('''') console.log(rgbToHex(0, 51, 255)); // ''#0033ff''

Tenga en cuenta que esta respuesta utiliza las últimas características de ECMAScript, que no son compatibles con los navegadores más antiguos. Si desea que este código funcione en todos los entornos, debe usar Babel para compilar su código.


Versión abreviada que acepta una cadena:

function rgbToHex(a){ a=a.replace(/[^/d,]/g,"").split(","); return"#"+((1<<24)+(+a[0]<<16)+(+a[1]<<8)+ +a[2]).toString(16).slice(1) } document.write(rgbToHex("rgb(255,255,255)"));

Para comprobar si no es ya hexadecimal.

function rgbToHex(a){ if(~a.indexOf("#"))return a; a=a.replace(/[^/d,]/g,"").split(","); return"#"+((1<<24)+(+a[0]<<16)+(+a[1]<<8)+ +a[2]).toString(16).slice(1) } document.write("rgb: "+rgbToHex("rgb(255,255,255)")+ " -- hex: "+rgbToHex("#e2e2e2"));


¿Puedes estar tras algo como esto?

function RGB2HTML(red, green, blue) { return ''#'' + red.toString(16) + green.toString(16) + blue.toString(16); } alert(RGB2HTML(150, 135, 200));

muestra # 9687c8


// Ignorando la notación hsl, los valores de color se expresan comúnmente como nombres, rgb, rgba o hex-

// Hex puede ser 3 valores o 6.

// Rgb puede ser tanto porcentajes como valores enteros.

// Mejor tener en cuenta todos estos formatos, al menos.

String.prototype.padZero= function(len, c){ var s= this, c= c || "0", len= len || 2; while(s.length < len) s= c + s; return s; } var colors={ colornames:{ aqua: ''#00ffff'', black: ''#000000'', blue: ''#0000ff'', fuchsia: ''#ff00ff'', gray: ''#808080'', green: ''#008000'', lime: ''#00ff00'', maroon: ''#800000'', navy: ''#000080'', olive: ''#808000'', purple: ''#800080'', red: ''#ff0000'', silver: ''#c0c0c0'', teal: ''#008080'', white: ''#ffffff'', yellow: ''#ffff00'' }, toRgb: function(c){ c= ''0x''+colors.toHex(c).substring(1); c= [(c>> 16)&255, (c>> 8)&255, c&255]; return ''rgb(''+c.join('','')+'')''; }, toHex: function(c){ var tem, i= 0, c= c? c.toString().toLowerCase(): ''''; if(/^#[a-f0-9]{3,6}$/.test(c)){ if(c.length< 7){ var A= c.split(''''); c= A[0]+A[1]+A[1]+A[2]+A[2]+A[3]+A[3]; } return c; } if(/^[a-z]+$/.test(c)){ return colors.colornames[c] || ''''; } c= c.match(//d+(/./d+)?%?/g) || []; if(c.length<3) return ''''; c= c.slice(0, 3); while(i< 3){ tem= c[i]; if(tem.indexOf(''%'')!= -1){ tem= Math.round(parseFloat(tem)*2.55); } else tem= parseInt(tem); if(tem< 0 || tem> 255) c.length= 0; else c[i++]= tem.toString(16).padZero(2); } if(c.length== 3) return ''#''+c.join('''').toLowerCase(); return ''''; } } //var c=''#dc149c''; //var c=''rgb(100%,25%,0)''; // var c= ''red''; alert(colors.toRgb(c)+''/n''+colors.toHex(c));


@ Tim, para agregar a tu respuesta (es un poco incómodo encajar esto en un comentario).

Tal como está escrito, encontré que la función rgbToHex devuelve una cadena con elementos después del punto y requiere que los valores r, g, b caigan dentro del rango 0-255.

Estoy seguro de que esto puede parecer obvio para la mayoría, pero tardé dos horas en darme cuenta y para entonces el método original se había disparado a 7 líneas antes de darme cuenta de que mi problema estaba en otra parte. Así que para ahorrar tiempo y problemas a los demás, aquí está mi código ligeramente modificado que verifica los requisitos previos y recorta los fragmentos extraños de la cadena.

function rgbToHex(r, g, b) { if(r < 0 || r > 255) alert("r is out of bounds; "+r); if(g < 0 || g > 255) alert("g is out of bounds; "+g); if(b < 0 || b > 255) alert("b is out of bounds; "+b); return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1,7); }


Aquí está mi versión:

function rgb2hex(red, green, blue) { var rgb = blue | (green << 8) | (red << 16); return ''#'' + (0x1000000 + rgb).toString(16).slice(1) } function hex2rgb(hex) { // long version r = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i); if (r) { return r.slice(1,4).map(function(x) { return parseInt(x, 16); }); } // short version r = hex.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i); if (r) { return r.slice(1,4).map(function(x) { return 0x11 * parseInt(x, 16); }); } return null; }


Encontré este problema porque quería aceptar cualquier valor de color y poder agregar una opacidad, así que hice este complemento rápido de jQuery que usa el lienzo nativo en los navegadores modernos. Parece funcionar muy bien.

Editar

Resulta que no puedo descubrir cómo convertirlo en un complemento de jQuery adecuado, así que lo presentaré como una función regular.

//accepts any value like ''#ffffff'', ''rgba(255,255,255,1)'', ''hsl(0,100%,100%)'', or ''white'' function toRGBA( c ) { var can = document.createElement( ''canvas'' ), ctx = can.getContext( ''2d'' ); can.width = can.height = 1; ctx.fillStyle = c; console.log( ctx.fillStyle ); //always css 6 digit hex color string, e.g. ''#ffffff'' ctx.fillRect( 0, 0, 1, 1 ); //paint the canvas var img = ctx.getImageData( 0, 0, 1, 1 ), data = img.data, rgba = { r: data[ 0 ], //0-255 red g: data[ 1 ], //0-255 green b: data[ 2 ], //0-255 blue a: data[ 3 ] //0-255 opacity (0 being transparent, 255 being opaque) }; return rgba; };


Encontré esto y porque creo que es bastante sencillo y tiene pruebas de validación y admite valores alfa (opcional), esto se ajustará al caso.

Solo comente la línea de expresiones regulares si sabe lo que está haciendo y es un poquito más rápido.

function hexToRGBA(hex, alpha){ hex = (""+hex).trim().replace(/#/g,""); //trim and remove any leading # if there (supports number values as well) if (!/^(?:[0-9a-fA-F]{3}){1,2}$/.test(hex)) throw ("not a valid hex string"); //Regex Validator if (hex.length==3){hex=hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]} //support short form var b_int = parseInt(hex, 16); return "rgba("+[ (b_int >> 16) & 255, //R (b_int >> 8) & 255, //G b_int & 255, //B alpha || 1 //add alpha if is set ].join(",")+")"; }


Este código acepta las variantes y opacidad de #fff y #ffffff.

function hex2rgb(hex, opacity) { var h=hex.replace(''#'', ''''); h = h.match(new RegExp(''(.{''+h.length/3+''})'', ''g'')); for(var i=0; i<h.length; i++) h[i] = parseInt(h[i].length==1? h[i]+h[i]:h[i], 16); if (typeof opacity != ''undefined'') h.push(opacity); return ''rgba(''+h.join('','')+'')''; }


Esto podría ser usado para obtener colores de propiedades de estilo computadas:

function rgbToHex(color) { color = ""+ color; if (!color || color.indexOf("rgb") < 0) { return; } if (color.charAt(0) == "#") { return color; } var nums = /(.*?)rgb/((/d+),/s*(/d+),/s*(/d+)/)/i.exec(color), r = parseInt(nums[2], 10).toString(16), g = parseInt(nums[3], 10).toString(16), b = parseInt(nums[4], 10).toString(16); return "#"+ ( (r.length == 1 ? "0"+ r : r) + (g.length == 1 ? "0"+ g : g) + (b.length == 1 ? "0"+ b : b) ); } // not computed <div style="color: #4d93bc; border: 1px solid red;">...</div> // computed <div style="color: rgb(77, 147, 188); border: 1px solid rgb(255, 0, 0);">...</div> console.log( rgbToHex(color) ) // #4d93bc console.log( rgbToHex(borderTopColor) ) // #ff0000

Refs:
https://github.com/k-gun/so/blob/master/so_util.js#L10
https://github.com/k-gun/so/blob/master/so_util.js#L62
https://github.com/k-gun/so/blob/master/so_util.js#L81


Estoy trabajando con datos XAML que tienen un formato hexadecimal de #AARRGGBB (Alpha, Red, Green, Blue). Usando las respuestas anteriores, aquí está mi solución:

function hexToRgba(hex) { var bigint, r, g, b, a; //Remove # character var re = /^#?/; var aRgb = hex.replace(re, ''''); bigint = parseInt(aRgb, 16); //If in #FFF format if (aRgb.length == 3) { r = (bigint >> 4) & 255; g = (bigint >> 2) & 255; b = bigint & 255; return "rgba(" + r + "," + g + "," + b + ",1)"; } //If in #RRGGBB format if (aRgb.length >= 6) { r = (bigint >> 16) & 255; g = (bigint >> 8) & 255; b = bigint & 255; var rgb = r + "," + g + "," + b; //If in #AARRBBGG format if (aRgb.length == 8) { a = ((bigint >> 24) & 255) / 255; return "rgba(" + rgb + "," + a.toFixed(1) + ")"; } } return "rgba(" + rgb + ",1)"; }

http://jsfiddle.net/kvLyscs3/


HTML usa el sistema hexadecimal y el rgb usa el sistema decimal. así que tienes que convertir el número de hexadecimal a decimal y viceversa.


La respuesta mejor calificada de Tim Down proporciona la mejor solución que puedo ver para la conversión a RGB. Sin embargo, me gusta más esta solución para la conversión a Hex porque proporciona la comprobación de límites más concisos y el relleno cero para la conversión a Hex.

function RGBtoHex (red, green, blue) { red = Math.max(0, Math.min(~~this.red, 255)); green = Math.max(0, Math.min(~~this.green, 255)); blue = Math.max(0, Math.min(~~this.blue, 255)); return ''#'' + (''00000'' + (red << 16 | green << 8 | blue).toString(16)).slice(-6); };

El uso del turno de la izquierda ''<<'' y o ''|'' los operadores hacen de esto una solución divertida también.


Lo siguiente será válido para la conversión de RGB a hexadecimal y agregará cualquier relleno cero requerido:

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

Convertir de otra manera:

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";

Finalmente, una versión alternativa de rgbToHex() , como se explica en la respuesta de @casablanca y se sugiere en los comentarios de @cwolves:

function rgbToHex(r, g, b) { return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); }

Actualización 3 diciembre 2012

Aquí hay una versión de hexToRgb() que también analiza un triplete hexadecimal abreviado como "# 03F":

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";


Mi versión de hex2rbg:

  1. Acepta hexágono corto como #fff
  2. La compacidad del algoritmo es o (n), debería ser más rápido que usar expresiones regulares. por ejemplo String.replace, String.split, String.match etc.
  3. Usa el espacio constante.
  4. Soporte rgb y rgba.

Es posible que necesite eliminar hex.trim () si está utilizando IE8.

p.ej

hex2rgb(''#fff'') //rgb(255,255,255) hex2rgb(''#fff'', 1) //rgba(255,255,255,1) hex2rgb(''#ffffff'') //rgb(255,255,255) hex2rgb(''#ffffff'', 1) //rgba(255,255,255,1)

código:

function hex2rgb (hex, opacity) { hex = hex.trim(); hex = hex[0] === ''#'' ? hex.substr(1) : hex; var bigint = parseInt(hex, 16), h = []; if (hex.length === 3) { h.push((bigint >> 4) & 255); h.push((bigint >> 2) & 255); } else { h.push((bigint >> 16) & 255); h.push((bigint >> 8) & 255); } h.push(bigint & 255); if (arguments.length === 2) { h.push(opacity); return ''rgba(''+h.join()+'')''; } else { return ''rgb(''+h.join()+'')''; } }


Necesitaba una función que acepta valores inválidos también como

rgb (-255, 255, 255) rgb (510, 255, 255)

Este es un spin off de la respuesta de @cwolves

function rgb(r, g, b) { this.c = this.c || function (n) { return Math.max(Math.min(n, 255), 0) }; return ((1 << 24) + (this.c(r) << 16) + (this.c(g) << 8) + this.c(b)).toString(16).slice(1).toUpperCase(); }


Para convertir directamente desde jQuery puedes probar:

function rgbToHex(color) { var bg = color.match(/^rgb/((/d+),/s*(/d+),/s*(/d+)/)$/); function hex(x) { return ("0" + parseInt(x).toString(16)).slice(-2); } return "#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]); } rgbToHex($(''.col-tab-bar .col-tab span'').css(''color''))


Para la función hexToRgb de 3 dígitos de Tim Down se puede mejorar de la siguiente manera:

var hex2Rgb = function(hex){ var result = /^#?([a-f/d]{2})([a-f/d]{2})([a-f/d]{2})|([a-f/d]{1})([a-f/d]{1})([a-f/d]{1})$/i.exec(hex); return result ? { r: parseInt(hex.length <= 4 ? result[4]+result[4] : result[1], 16), g: parseInt(hex.length <= 4 ? result[5]+result[5] : result[2], 16), b: parseInt(hex.length <= 4 ? result[6]+result[6] : result[3], 16), toString: function() { var arr = []; arr.push(this.r); arr.push(this.g); arr.push(this.b); return "rgb(" + arr.join(",") + ")"; } } : null; };


Si bien es poco probable que esta respuesta se ajuste perfectamente a la pregunta, puede ser muy útil, no obstante.

  1. Crea cualquier elemento aleatorio

var toRgb = document.createElement(''div'');

  1. Configura cualquier estilo válido al color que quieras convertir.

toRg.style.color = "hsl(120, 60%, 70%)";

  1. Llame a la propiedad de estilo de nuevo

> toRgb.style.color;

< "rgb(133, 225, 133)" Su color se ha convertido a Rgb

Obras para: Hsl, Hex.

No funciona para: colores con nombre.


Si necesita comparar dos valores de color (dados como rgb, nombre de color o valor hexadecimal) o convertir a HEX use el objeto de lienzo HTML5.

var canvas = document.createElement("canvas"); var ctx = this.canvas.getContext(''2d''); ctx.fillStyle = "rgb(pass,some,value)"; var temp = ctx.fillStyle; ctx.fillStyle = "someColor"; alert(ctx.fillStyle == temp);


Supongo que te refieres a la notación hexadecimal de estilo HTML, es decir, #rrggbb . Su código es casi correcto, excepto que tiene la orden invertida. Debería ser:

var decColor = red * 65536 + green * 256 + blue;

Además, el uso de desplazamientos de bits puede facilitar la lectura:

var decColor = (red << 16) + (green << 8) + blue;


Teniendo en cuenta que muchas respuestas solo responden parcialmente a la pregunta (ya sea de RGB a HEX o al revés), pensé que también publicaría mi respuesta parcial.

Tuve un problema similar y quería hacer algo como esto: ingresar cualquier color CSS válido (HSL (a), RGB (a), HEX o nombre de color) y 1. poder agregar o eliminar un valor alfa, 2. devuelve un objeto rgb (a). Escribí un plugin exactamente para este propósito. Se puede encontrar en GitHub (requiere jQuery, pero si lo deseas, puedes hacerlo y hacer una versión de vainilla). Aquí hay una página de demostración . Puedes probar por ti mismo y ver la salida generada sobre la marcha.

Copiaré y pegaré las opciones aquí:

RGB Generator acepta un argumento, el color, y proporciona tres opciones: asObject, addAlpha y removeAlpha. Cuando se omiten las tres opciones, el color RGB se devolverá como una cadena.

$.rgbGenerator("white") // Will return rgb(255,255,255)

Tenga en cuenta que por defecto están incluidos los componentes alfa. Si el valor de entrada contiene un valor alfa, la salida estará en formato RGBa.

$.rgbGenerator("hsla(0,100%,50%,0.8)") // Will return rgba(255,0,0,0.8)

Puedes deshabilitar este comportamiento configurando removeAlpha en verdadero. Esto eliminará cualquier valor alfa de un color inicial HSLa o RGBa.

$.rgbGenerator("hsla(0,100%,50%,0.8)", {removeAlpha: true}) // Will return rgb(255,0,0)

Si, por otro lado, desea agregar un canal alfa, puede hacerlo configurando addAlpha en cualquier valor entre 0 y 1. Cuando la entrada no sea un color transparente, se agregará el valor alfa. Si es transparente, el valor proporcionado sobrescribirá el componente alfa de la entrada.

$.rgbGenerator("hsl(0,100%,50%)", {addAlpha: 0.4}) // Will return rgba(255,0,0,0.4) $.rgbGenerator("hsla(0,100%,50%,0.8)", {addAlpha: 0.4}) // Will return rgba(255,0,0,0.4)

Finalmente, también es posible generar el color RGB (a) como un objeto. Constará de r, g, b y opcionalmente a.

$.rgbGenerator("hsla(0,100%,50%,0.8)", {asObject: true}) /* Will return { "r": 255, "g": 0, "b": 0, "a": 0.8 } */ $.rgbGenerator("hsla(0,100%,50%,0.8)", {asObject: true}).r // Will return 255


Una versión alternativa de hexToRgb:

function hexToRgb(hex) { var bigint = parseInt(hex, 16); var r = (bigint >> 16) & 255; var g = (bigint >> 8) & 255; var b = bigint & 255; return r + "," + g + "," + b; }

Edit: 28/03/2017 Aquí hay otro enfoque. eso parece ser incluso más rápido

function hexToRgbNew(hex) { var arrBuff = new ArrayBuffer(4); var vw = new DataView(arrBuff); vw.setUint32(0,parseInt(hex, 16),false); var arrByte = new Uint8Array(arrBuff); return arrByte[1] + "," + arrByte[2] + "," + arrByte[3]; }

Edit: 11/08/2017 El nuevo enfoque anterior después de más pruebas no es más rápido :(. Aunque es una forma alternativa divertida.


(2017) SIMPLE ES6 funciones de flecha componibles

No puedo resistirme a compartir esto con aquellos que pueden estar escribiendo algunos js funcionales / compositivos modernos utilizando ES6. A continuación, se detallan algunas líneas sencillas que estoy usando en un módulo de color que realiza la interpolación de colores para la visualización de datos.

Tenga en cuenta que esto no controla el canal alfa en absoluto.

const arrayToRGBString = rgb => `rgb(${rgb.join('','')})`; const hexToRGBArray = hex => hex.match(/[A-Za-z0-9]{2}/g).map(v => parseInt(v, 16)); const rgbArrayToHex = rgb => `#${rgb.map(v => v.toString(16).padStart(2, ''0'')).join('''')}`; const rgbStringToArray = rgb => rgb.match(/^rgb/((/d+),/s*(/d+),/s*(/d+)/)$/).splice(1, 3) .map(v => Number(v)); const rgbStringToHex = rgb => rgbArrayToHex(rgbStringToArray(rgb));


HEX funcional de una línea a RGBA

Admite #fff cortas #fff y largas #ffffff .
Soporta canal alfa (opacidad).
No importa si hash especificado o no, funciona en ambos casos.

function hexToRGBA(hex, opacity) { return ''rgba('' + (hex = hex.replace(''#'', '''')).match(new RegExp(''(.{'' + hex.length/3 + ''})'', ''g'')).map(function(l) { return parseInt(hex.length%2 ? l+l : l, 16) }).concat(opacity||1).join('','') + '')''; }

ejemplos:

hexToRGBA(''#fff'') -> rgba(255,255,255,1) hexToRGBA(''#ffffff'') -> rgba(255,255,255,1) hexToRGBA(''#fff'', .2) -> rgba(255,255,255,0.2) hexToRGBA(''#ffffff'', .2) -> rgba(255,255,255,0.2) hexToRGBA(''fff'', .2) -> rgba(255,255,255,0.2) hexToRGBA(''ffffff'', .2) -> rgba(255,255,255,0.2)


Un enfoque totalmente diferente para convertir el código de color hexadecimal a RGB sin expresiones regulares

Maneja los formatos #FFF y #FFFFFF en la base de la longitud de la cadena. Elimina # del comienzo de la cadena y divide cada carácter de la cadena, la convierte en base10 y la agrega al índice respectivo en la base de su posición.

//Algorithm of hex to rgb conversion in ES5 function hex2rgbSimple(str){ str = str.replace(''#'', ''''); return str.split('''').reduce(function(result, char, index, array){ var j = parseInt(index * 3/array.length); var number = parseInt(char, 16); result[j] = (array.length == 3? number : result[j]) * 16 + number; return result; },[0,0,0]); } //Same code in ES6 hex2rgb = str => str.replace(''#'','''').split('''').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0]); //hex to RGBA conversion hex2rgba = (str, a) => str.replace(''#'','''').split('''').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0,a||1]); //hex to standard RGB conversion hex2rgbStandard = str => `RGB(${str.replace(''#'','''').split('''').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0]).join('','')})`; console.log(hex2rgb(''#aebece'')); console.log(hex2rgbSimple(''#aebece'')); console.log(hex2rgb(''#aabbcc'')); console.log(hex2rgb(''#abc'')); console.log(hex2rgba(''#abc'', 0.7)); console.log(hex2rgbStandard(''#abc''));


R = HexToR("#FFFFFF"); G = HexToG("#FFFFFF"); B = HexToB("#FFFFFF"); function HexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)} function HexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)} function HexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)} function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}

Utilice estas funciones para lograr el resultado sin ningún problema. :)


function getRGB(color){ if(color.length == 7){ var r = parseInt(color.substr(1,2),16); var g = parseInt(color.substr(3,2),16); var b = parseInt(color.substr(5,2),16); return ''rgb(''+r+'',''+g+'',''+b+'')'' ; } else console.log(''Enter correct value''); } var a = getRGB(''#f0f0f0''); if(!a){ a = ''Enter correct value''; } a;


function hex2rgb(hex) { return [''0x'' + hex[1] + hex[2] | 0, ''0x'' + hex[3] + hex[4] | 0, ''0x'' + hex[5] + hex[6] | 0]; }


function hexToRgb(str) { if ( /^#([0-9a-f]{3}|[0-9a-f]{6})$/ig.test(str) ) { var hex = str.substr(1); hex = hex.length == 3 ? hex.replace(/(.)/g, ''$1$1'') : hex; var rgb = parseInt(hex, 16); return ''rgb('' + [(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255].join('','') + '')''; } return false; } function rgbToHex(red, green, blue) { var out = ''#''; for (var i = 0; i < 3; ++i) { var n = typeof arguments[i] == ''number'' ? arguments[i] : parseInt(arguments[i]); if (isNaN(n) || n < 0 || n > 255) { return false; } out += (n < 16 ? ''0'' : '''') + n.toString(16); } return out