You could
- create a new Element using javascript.
- set its background-color o.s. style to the input value
- append it to the body
- get its
window.getComputedStyle
note: compatibility
- return the equivalent
backgroundColor
o.s.
function getRGB(v) {
var el = document.createElement("div");
el.style["background-color"] = v;
document.body.appendChild(el);
var style = window.getComputedStyle(el);
var color = style["backgroundColor"];
document.body.removeChild(el);
return color;
}
getRGB ("red") //"rgb(255, 0, 0)"
But note: as Cristoph says you can't say for sure to always get the right value
Though it works quite well for me on Chrome
But i don't think you can get it the other way round with out a Map, like Cristoph suggests
Demon on JSBin
Update
Here is a function with a complete map which returns color Objects that contain hex,named,and rgb represantations of the color.
function getColor (r,g,b) {
var colors = {TooBigToPostHere:...} //see the JSBin
function rgbToHex(r, g, b) {
var hex = "#";
for (var i = 0; i < 3; i++) {
var _hex = arguments[i].toString(16);
while (_hex.length < 2) _hex = "0" + _hex;
hex += _hex
}
return hex.toUpperCase();
}
if (typeof r === "string") r = r["to"+(!!~r.indexOf("#")?"Upper":"Lower")+"Case"]();
if (r in colors) return colors[r]
else if (r !== undefined && g !== undefined && b !== undefined) {
var hex = rgbToHex(r, g, b);
if (hex in colors) return colors[hex]
else return {
rgb: [r, g, b],
hex: hex,
name: null
}
} else {
throw new SyntaxError("Invalid Arguments");
}
}
Which produces this output:
console.log ( getColor (245,245,245)) //{"hex": "#F5F5F5", "name": "whitesmoke", "rgb": [245, 245, 245]}
console.log ( getColor ("#EE82EE")); //{"hex": "#EE82EE", "name": "violet", "rgb": [238, 130, 238]}
console.log ( getColor ("red")); //{"hex": "#FF0000", "name": "red", "rgb": [255, 0, 0]}
And a Demo on JSBin
Note: colors contains the complete list of Extended color keywords
Heres the code i used to scrape the above color table
var colors = {};
[].forEach.call(document.querySelectorAll (".colortable tr"), function (e,i) {
if ( i > 0 ) {
var hex = e.children[3].innerText;
colors[hex] = {};
colors[hex].hex = hex;
colors[hex].name = e.children[2].innerText;
colors[hex].rgb = e.children[4].innerText.split(",");
colors[hex].rgb.map(function (a,b,c) {c[b] = +a})
colors[colors[hex].name] = colors[hex];
}
});