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?
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With