Home  >  Q&A  >  body text

How to get the RGB value of CSS/HTML named color in JavaScript

I have created a Javascript object named [name-rgb]. Your basics:

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

Object. But I realized that I should be able to input a name string, say "AliceBlue", and have JavaScript find some sort of RGB representation of it (hex would work too). I know there are at least 140 hidden named colors in browsers, but I can't seem to find them.

Is there a CSS or "style=..." technique that allows me to find the RGB representation of a color name?

P粉557957970P粉557957970348 days ago702

reply all(2)I'll reply

  • P粉052724364

    P粉0527243642023-11-07 00:10:54

    This is the solution I finally came up with. I realize that there are two types of colors: css strings and webgl type arrays (usually 4 floats or integers, depending on the situation).

    Forget it, let the browser handle it: create a 1x1 canvas, fill it with any string color, get the pixels, and deconstruct it into an rgba array. Below are two utilities for creating 1x1 2d canvas ctx.

    #根据任何合法的CSS颜色返回一个RGB数组,否则返回null。
    #http://www.w3schools.com/cssref/css_colors_legal.asp
    #字符串可以是CadetBlue,#0f0,rgb(255,0,0),hsl(120,100%,50%)
    #rgba/hsla形式也可以,但我们不返回a。
    #注意:浏览器自己说话:我们只需将1x1的画布fillStyle设置为字符串并创建一个像素,返回r,g,b值。
    #警告:r=g=b=0可能表示非法字符串。我们测试了一些明显的情况,但要注意意外的[0,0,0]结果。
    ctx1x1: u.createCtx 1, 1 #跨调用共享。闭包封装更好吗?
    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 like about it is that the browser speaks for itself. Any legal string will work fine. The only downside is that if the string is illegal, you'll get black, so some checking needs to be done. The error checking isn't great, but I don't need it in my usage.

    Utility functions:

    #创建一个给定宽度/高度的新画布
    createCanvas: (width, height) ->
      can = document.createElement 'canvas'
      can.width = width; can.height = height
      can
    #与上述相同,但返回上下文对象。
    #注意ctx.canvas是ctx的画布,可以用作图像。
    createCtx: (width, height) ->
      can = @createCanvas width, height
      can.getContext "2d"

    reply
    0
  • P粉311617763

    P粉3116177632023-11-07 00:08:14

    The simplest JavaScript function:

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

    reply
    0
  • Cancelreply