4

I would like to write a javascript program to get the rgb color for the defined color words in css.

So for example, if I type in red, I would like to output rgb(255, 0, 0). I would also like to convert from rgb(255, 0, 0) to red.

Is there a way to do this in javascript?

Alexis
  • 23,545
  • 19
  • 104
  • 143
  • 2
    Not my downvote. rgb(51, 51, 51) is (a bit dark) grey. Red is 255,0,0 – zkanoca May 29 '13 at 08:10
  • 3
    well, the easiest and most reliable way would surely be to have a mapping object to map all colors to all rgb values. – Christoph May 29 '13 at 08:10
  • `rgb(51, 51, 51)` is grey. RGB is an abbreviation of Red Green Blue. `rgb(red, green, blue)`. Red, therefore, is `rgb(255, 0, 0)`. – James Donnelly May 29 '13 at 08:10
  • Half of your question is answered here: http://stackoverflow.com/questions/1573053/javascript-function-to-convert-color-names-to-hex-codes – Salman A May 29 '13 at 08:12
  • @Christoph yes but I want to do it programmatically – Alexis May 29 '13 at 08:13
  • 1
    And here is the other half: http://stackoverflow.com/questions/9224404/get-color-name-by-hex-or-rgb (marking as duplicate) – Salman A May 29 '13 at 08:16
  • @SalmanA note, that the color classifier lists color which are not available in the browser! The webcolors are: http://dev.w3.org/csswg/css-color/#svg-color while there are a lot more colors available for "non-web": http://en.wikipedia.org/wiki/List_of_colors – Christoph May 29 '13 at 08:34
  • @Scoop i added an example with a complete map of colors – Moritz Roessler May 29 '13 at 09:42

3 Answers3

4

This can't be accomplished easily programatically, because browsers differ in their behaviour. You can't say for sure whether they return the original value (e.g. your word) or the computed hex or rgb value. (It is possible, though with getComputedStyle()!)

In every case you won't get the color word for your rgb/hex/hsl value. (At least I'm not aware of this being possible).

The "easiest", reliable way would be to create a mapping object which hold all color words and their respective values. You can find the list here:

http://dev.w3.org/csswg/css-color/#svg-color

var word2value = {
       red: {"hex":"#FF0000","rgb":"255,0,0"},
       /* ... all other values */
}

var value2word = {
       "FF0000" : "red",
       "255,0,0": "red"
}

note, you need to access via bracket notation: value2word["255,0,0"]

Christoph
  • 50,121
  • 21
  • 99
  • 128
2

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];
 }
});
Moritz Roessler
  • 8,542
  • 26
  • 51
2

I think this is what you want:

Text:
<input type="text" id="ctext" />
<br>RGB:
<input type="text" id="crgb" />
<br>
<button onclick="doMagic();">Magic</button>
<div id="output" style="display:none"></div>
<script>
    function doMagic() {
        $('#output').html('<p id=test style=\'color:' + $('#ctext').val() + ';\'>sometext</p>');
        $('#crgb').val($('#test').css("color"));
    }
</script>

Check it out on fiddle .

I think it works great!

MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125