简体   繁体   English

在 JavaScript 中获取名为 color 的 CSS/HTML 的 RGB 值

[英]Getting the RGB values for a CSS/HTML named color in JavaScript

I've built a name-[rgb] Javascript object.我已经构建了一个 name-[rgb] Javascript 对象。 Your basic:你的基本:

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

object.目的。 But it occurred to me that I should be able to take a name string, "AliceBlue", say .. and have JavaScript find some sort of RGB representation of it (hex is fine).但我突然想到,我应该能够取一个名称字符串“AliceBlue”,比如说.. 并让 JavaScript 找到它的某种 RGB 表示形式(十六进制很好)。 I know there are at least 140 named colors tucked away in the browser, but I can't seem to find them.我知道浏览器中至少有 140 种命名颜色,但我似乎找不到它们。

Is there a CSS or "style=..." stunt that lets me look up an RGB representation of a color name?是否有 CSS 或“style=...”特技可以让我查找颜色名称的 RGB 表示?

Minimal JavaScript function:最小的 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;
}

This is the solution I ended up with.这是我最终得到的解决方案。 I realized that colors came in two types: css strings and webgl typed arrays (usually 4 floats or ints, depending).我意识到颜色有两种类型:css 字符串和 webgl 类型的数组(通常是 4 个浮点数或整数,具体取决于)。

Hell with it, let the browser figure it: create a 1x1 canvas, fill it with any string color, grab the pixel, and destructure into an rgba array.见鬼去吧,让浏览器想办法:创建一个 1x1 画布,用任何字符串颜色填充它,抓取像素,然后解构为一个 rgba 数组。 There are two utilities below that create the 1x1 2d canvas ctx, attached.下面有两个实用程序可以创建 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

What I love about it is that The Browser Speaks For Itself.我喜欢它的是浏览器会说话。 Any legal string works just fine.任何合法的字符串都可以正常工作。 Only downside is that if the string is illegal you get black, so need to do a few checks.唯一的缺点是如果字符串是非法的,你会得到黑色,所以需要做一些检查。 The error checking is not great, but I don't need it in my usage.错误检查不是很好,但我在使用中不需要它。

The utility functions:实用功能:

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

使用函数“name2hex”和“name2rgb”查看Colors.js ,该库返回颜色名称的 hex 或 rgb 值。

You can use a canvas to get the RGBA color from a name.您可以使用画布从名称中获取 RGBA 颜色。

Please look at this fiddle: https://jsfiddle.net/AaronWatters/p1y298zk/19/请看这个小提琴: 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);

This is how jp_doodle does color interpolation in transitions: https://aaronwatters.github.io/jp_doodle/080_transitions.html这就是 jp_doodle 在过渡中进行颜色插值的方式: https ://aaronwatters.github.io/jp_doodle/080_transitions.html

The following might do the trick if you have an integer representation:如果您有整数表示,以下可能会奏效:

function getHex(color){
    return "#"+color.map(function(x){return x.toString(16).toUpperCase();}).join("");
}

Here is the Fiddle .这是小提琴

For the rest, you could create an element and take its colour.其余的,您可以创建一个元素并获取其颜色。

el=document.createElement("DIV");
el.style.backgroundColor="aliceblue";
console.log(el.style.backgroundColor);

Fiddle for that那个小提琴

Other approaches on this page use HTML5 Canvas .此页面上的其他方法使用HTML5 Canvas

But it's straightforward (once you know how) to derive the rgb() value from a color keyword simply by inspecting standard <div> .但是,只需检查标准<div>就可以直接(一旦您知道如何)从颜色关键字派生rgb()值。

The method used to resolve the rgb() value in this approach is:此方法中用于解析rgb()值的方法是:

  • window.getComputedStyle()

Working Example:工作示例:

 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'));


Further Reading:延伸阅读:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM