在JavaScript中获取CSS/HTML命名颜色的RGB值

4

我已经创建了一个名为-[rgb]的 JavaScript 对象。它的基本形式如下:

namedColors = {
  AliceBlue: [240, 248, 255],
  AntiqueWhite: [250, 235, 215],
  ...

对象。但是我意识到,我应该能够使用名称字符串,比如说"AliceBlue",然后让JavaScript找到它的RGB表示方式(十六进制也可以)。我知道浏览器中至少有140种命名颜色,但我似乎找不到它们。

是否有CSS或"style=..."技巧可以让我查找颜色名称的RGB表示?


我不确定你的长期目标是什么,但也有一些“跳出常规思维”的解决方案。如果我没记错的话,你可以在创建的DOM元素上设置命名颜色,然后检查计算样式...我相信所有返回RGB值。 - scunliffe
2
可能是 Javascript 函数将颜色名称转换为十六进制代码 的重复。 - Bojan Petkovski
使用JavaScript或jQuery很容易实现...但你是否想要一个仅基于CSS的解决方案? - dhc
dhc:是的..一个简单的函数 nameToRGB(name) -> 任何一种rgb表示,如十六进制字符串或rgb字符串。 - backspaces
scunliffe, bojan:是的,另一个SO是重复的,而getComputedStyles方法看起来很有前途。我会试一试。这是我认为能解决问题的指针:http://www.backalleycoder.com/2010/10/05/converting-css-named-colors-to-rgb-and-hex/ - backspaces
5个回答

7

最简单的JavaScript函数:

function nameToRgba(name) {
    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');
    context.fillStyle = name;
    context.fillRect(0,0,1,1);
    return context.getImageData(0,0,1,1).data;
}

你为什么发表了基本上与3年前已经发布的答案相同的回答? - Mike 'Pomax' Kamermans
我在寻找一个最小的JavaScript函数,可以复制和粘贴时发现了这篇文章,其他答案都没有提供这样的函数。我相信我的回答增加了一些价值。 - will
1
你的帖子很有价值,Will。这是一个简单而实用的答案。谢谢。 - Myndex
我也更喜欢这个完整的解决方案。 - backspaces

4
这是我最终得出的解决方案。我意识到颜色有两种类型:CSS字符串和WebGL类型数组(通常为4个浮点数或整数,具体取决于不同情况)。
与其自己琢磨,还不如让浏览器来处理:创建一个1x1的画布,填充任何颜色,获取像素值并将其解构成rgba数组。下面有两个实用程序,会创建附加在其中的1x1 2d画布ctx。
# Return an RGB array given any legal CSS color, null otherwise.
# http://www.w3schools.com/cssref/css_colors_legal.asp
# The string can be CadetBlue, #0f0, rgb(255,0,0), hsl(120,100%,50%)
# The rgba/hsla forms ok too, but we don't return the a.
# Note: The browser speaks for itself: we simply set a 1x1 canvas fillStyle
# to the string and create a pixel, returning the r,g,b values.
# Warning: r=g=b=0 can indicate an illegal string.  We test
# for a few obvious cases but beware of unexpected [0,0,0] results.
ctx1x1: u.createCtx 1, 1 # share across calls. closure wrapper better?
stringToRGB: (string) ->
  @ctx1x1.fillStyle = string
  @ctx1x1.fillRect 0, 0, 1, 1
  [r, g, b, a] = @ctx1x1.getImageData(0, 0, 1, 1).data
  return [r, g, b] if (r+g+b isnt 0) or
    (string.match(/^black$/i)) or
    (string in ["#000","#000000"]) or
    (string.match(/rgba{0,1}\(0,0,0/i)) or
    (string.match(/hsla{0,1}\(0,0%,0%/i))
  null

我喜欢的是浏览器本身就有语音功能。任何合法字符串都可以正常工作。唯一的缺点是,如果字符串非法,你会得到黑色,所以需要进行一些检查。错误检查不太好,但在我的使用中不需要它。

实用函数:

# Create a new canvas of given width/height
createCanvas: (width, height) ->
  can = document.createElement 'canvas'
  can.width = width; can.height = height
  can
# As above, but returing the context object.
# Note ctx.canvas is the canvas for the ctx, and can be use as an image.
createCtx: (width, height) ->
  can = @createCanvas width, height
  can.getContext "2d"

1
这与JS无关,因此作为JavaScript问题的答案并不是非常好。人们可能可以想出如何使用真正的JS重新实现它,但最好还是展示原生JS实现。 - Mike 'Pomax' Kamermans

2

本页面中的其他方法使用HTML5 Canvas

但一个简单的替代方案是使用以下方式从任何颜色关键字派生rgb()值:

  • window.getComputedStyle()

工作示例:

const colorKeywordToRGB = (colorKeyword) => {

  // CREATE TEMPORARY ELEMENT
  let el = document.createElement('div');

  // APPLY COLOR TO TEMPORARY ELEMENT
  el.style.color = colorKeyword;

  // APPEND TEMPORARY ELEMENT
  document.body.appendChild(el);

  // RESOLVE COLOR AS RGB() VALUE
  let rgbValue = window.getComputedStyle(el).color;
  
  // REMOVE TEMPORARY ELEMENT
  document.body.removeChild(el);

  return rgbValue;
}

// BASIC COLORS
console.log('red:', colorKeywordToRGB('red'));
console.log('green:', colorKeywordToRGB('green'));
console.log('yellow:', colorKeywordToRGB('yellow'));
console.log('blue:', colorKeywordToRGB('blue'));

// SIMPLE COLORS
console.log('fuchsia:', colorKeywordToRGB('fuchsia'));
console.log('lime:', colorKeywordToRGB('lime'));
console.log('maroon:', colorKeywordToRGB('maroon'));
console.log('navy:', colorKeywordToRGB('navy'));
console.log('olive:', colorKeywordToRGB('olive'));
console.log('purple:', colorKeywordToRGB('purple'));
console.log('teal:', colorKeywordToRGB('teal'));
console.log('transparent:', colorKeywordToRGB('transparent'));

// ADVANCED COLORS
console.log('blanchedalmond:', colorKeywordToRGB('blanchedalmond'));
console.log('coral:', colorKeywordToRGB('coral'));
console.log('darkorchid:', colorKeywordToRGB('darkorchid'));
console.log('firebrick:', colorKeywordToRGB('firebrick'));
console.log('gainsboro:', colorKeywordToRGB('gainsboro'));
console.log('honeydew:', colorKeywordToRGB('honeydew'));
console.log('papayawhip:', colorKeywordToRGB('papayawhip'));
console.log('seashell:', colorKeywordToRGB('seashell'));
console.log('thistle:', colorKeywordToRGB('thistle'));
console.log('wheat:', colorKeywordToRGB('wheat'));


更多阅读:


1
你可以使用画布从名称中获取RGBA颜色。
请查看此fiddle:https://jsfiddle.net/AaronWatters/p1y298zk/19/
// We want to know the rgba values for this color name:
var testColor = "salmon"

// make a canvas
var canvas = $('<canvas width="100px" height="100px">');

// optional: display the canvas
var body = $(document.body);
canvas.appendTo(body);

// draw a rectangle on the canvas
var context = canvas[0].getContext("2d");
context.beginPath();
context.rect(0,0,100,100);
context.fillStyle = testColor;
context.fill();

// get the canvas image as an array
var imgData = context.getImageData(0, 0, 10, 10);
// rbga values for the element in the middle
var array = imgData.data.slice(50*4, 50*4+4);
// convert the opacity to 0..1
array[3] = array[3] / 255.0;

$("<div>The rgba for " + testColor + " is " + array + "</div>").appendTo(body);

这是jp_doodle在转换中进行颜色插值的方式:https://aaronwatters.github.io/jp_doodle/080_transitions.html

请注意,使用100x100画布没有必要,1x1画布也可以很好地完成任务,并且无需切片。const [r, g, b, a ] = Array.from(context.getImageData(0, 0, 1, 1).data); 然后是 return { r, g, b, a:a/255 }; 不过这基本上就是在4年前发布的答案,只是使用了WebGL而不是2D。 - Mike 'Pomax' Kamermans
我对矩形边缘的抗锯齿效果不确定,所以我使用了更大的画布来确保安全。 - Aaron Watters

1

请查看Colors.js,其中包含“name2hex”和“name2rgb”函数,该库将返回您颜色名称的十六进制或RGB值。


Colors.name2hex 看起来很有前途,但是我看了一下,它只是一个带有命名颜色及其十六进制值列表的工具。唉。 - backspaces

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接