从颜色词中获取颜色代码

Get color code from color word

本文关键字:颜色 代码 获取      更新时间:2023-09-26

我想写一个javascript程序来获取css中定义的颜色词的rgb颜色。

例如,如果我输入red,我想输出rgb(255, 0, 0)。我还想从rgb(255, 0, 0)转换为red

在javascript中有办法做到这一点吗?

这无法通过编程方式轻松完成,因为浏览器的行为不同。你不能确定它们是返回原始值(例如你的单词)还是计算的十六进制或rgb值。(这是可能的,尽管有getComputedStyle() !)

在任何情况下,都不会获得rgb/hex/hsl值的颜色词。(至少我不知道这是可能的)。

"最简单"、可靠的方法是创建一个包含所有颜色词及其各自值的映射对象。你可以在这里找到列表:

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

注意,您需要通过括号符号访问:value2word["255,0,0"]

我想这就是你想要的:

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>

在小提琴上看看。

我觉得它很好用!

你可以

  • 使用javascript创建一个新元素。
  • 设置其背景色os样式为输入值
  • 将其附加到正文
  • 获取window.getComputedStyle 注意:兼容性
  • 返回等效的backgroundColor

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

但注意:正如christoph所说,你不能保证总是得到正确的值

但是我不认为你可以像Cristoph建议的那样,没有地图就可以得到它

Demon on JSBin

<标题> 更新

这是一个带有完整映射的函数,它返回颜色对象,这些对象包含颜色的十六进制、命名和rgb表示。

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");
 }
}

产生如下输出:

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

和JSBin上的演示
注意:colors包含扩展颜色关键字的完整列表

下面是我用来抓取上面颜色表的代码
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];
 }
});