Skip to content

Instantly share code, notes, and snippets.

@maccman
Created December 3, 2012 16:52
Show Gist options
  • Save maccman/4196275 to your computer and use it in GitHub Desktop.
Save maccman/4196275 to your computer and use it in GitHub Desktop.
class Color
@regex: /(?:#([0-9a-f]{3,6})|rgba?\(([^)]+)\))/i
@fromHex: (hex) ->
if hex[0] is '#'
hex = hex.substring(1, 7)
if hex.length is 3
hex = hex.charAt(0) + hex.charAt(0) +
hex.charAt(1) + hex.charAt(1) +
hex.charAt(2) + hex.charAt(2)
r = parseInt(hex.substring(0,2), 16)
g = parseInt(hex.substring(2,4), 16)
b = parseInt(hex.substring(4,6), 16)
new this(r, g, b)
@fromString: (str) ->
match = str.match(@regex)
return null unless match
if hex = match[1]
@fromHex(hex)
else if rgba = match[2]
[r, g, b, a] = rgba.split(/\s*,\s*/)
new this(r, g, b, a)
constructor: (r, g, b, a = 1) ->
@r = parseInt(r, 10) if r?
@g = parseInt(g, 10) if g?
@b = parseInt(b, 10) if b?
@a = parseFloat(a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment