You could
- create a new element using javascript.
- set background color os style to input value
- attach it to the body
- get
window.getComputedStyle note: compatibility - return equivalent of
backgroundColor os
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")
But note: as Christoph says you cannot say for sure that you always need to have the right meaning
Although this works fine for me in Chrome
But I donβt think you can get it in reverse order with the Card, as Christophe says.
JSBin daemon
Update
Here is a full-mapping function that returns colored objects containing hexadecimal, registered, and rgb representations of 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"); } }
What produces this conclusion:
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 contain a complete list of advanced color keywords
Here is the code I used to clear the color table above.
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]; } });