Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get color code from color word [duplicate]

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?

like image 744
Alexis Avatar asked Feb 16 '23 09:02

Alexis


1 Answers

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

like image 101
Christoph Avatar answered Feb 26 '23 19:02

Christoph