这是我最终得出的解决方案。我意识到颜色有两种类型:CSS字符串和WebGL类型数组(通常为4个浮点数或整数,具体取决于不同情况)。
与其自己琢磨,还不如让浏览器来处理:创建一个1x1的画布,填充任何颜色,获取像素值并将其解构成rgba数组。下面有两个实用程序,会创建附加在其中的1x1 2d画布ctx。
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
我喜欢的是浏览器本身就有语音功能。任何合法字符串都可以正常工作。唯一的缺点是,如果字符串非法,你会得到黑色,所以需要进行一些检查。错误检查不太好,但在我的使用中不需要它。
实用函数:
createCanvas: (width, height) ->
can = document.createElement 'canvas'
can.width = width; can.height = height
can
createCtx: (width, height) ->
can = @createCanvas width, height
can.getContext "2d"