簡體   English   中英

在 JavaScript 中獲取名為 color 的 CSS/HTML 的 RGB 值

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

我已經構建了一個 name-[rgb] Javascript 對象。 你的基本:

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

目的。 但我突然想到,我應該能夠取一個名稱字符串“AliceBlue”,比如說.. 並讓 JavaScript 找到它的某種 RGB 表示形式(十六進制很好)。 我知道瀏覽器中至少有 140 種命名顏色,但我似乎找不到它們。

是否有 CSS 或“style=...”特技可以讓我查找顏色名稱的 RGB 表示?

最小的 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;
}

這是我最終得到的解決方案。 我意識到顏色有兩種類型: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"

使用函數“name2hex”和“name2rgb”查看Colors.js ,該庫返回顏色名稱的 hex 或 rgb 值。

您可以使用畫布從名稱中獲取 RGBA 顏色。

請看這個小提琴: 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

如果您有整數表示,以下可能會奏效:

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

這是小提琴

其余的,您可以創建一個元素並獲取其顏色。

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

那個小提琴

此頁面上的其他方法使用HTML5 Canvas

但是,只需檢查標准<div>就可以直接(一旦您知道如何)從顏色關鍵字派生rgb()值。

此方法中用於解析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'));


延伸閱讀:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM