Skip to content

Instantly share code, notes, and snippets.

@hitsujixgit
Created January 22, 2015 01:52
Show Gist options
  • Save hitsujixgit/1288d20c5499ce075770 to your computer and use it in GitHub Desktop.
Save hitsujixgit/1288d20c5499ce075770 to your computer and use it in GitHub Desktop.
Convert color systems
hex2rgb = (hexcode) ->
# rgbに変換する
result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hexcode);
if result is null
console.log "error!"
return
[r,g,b] = [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)]
return [r,g,b]
hsv2rgb = (h,s,v) ->
if h < 0
r = 0
g = 0
b = 0
else
h_dash = h / 60
x = s * (1 - Math.abs(h_dash % 2 - 1))
if h_dash < 1
[r,g,b] = [s,x,0]
else if h_dash < 2
[r,g,b] = [x,s,0]
else if h_dash < 3
[r,g,b] = [0,s,x]
else if h_dash < 4
[r,g,b] = [0,x,s]
else if h_dash < 5
[r,g,b] = [x,0,s]
else if h_dash < 6
[r,g,b] = [s,0,x]
else
console.log '変換エラー'
return
r += (v-s)
g += (v-s)
b += (v-s)
r *= 255
g *= 255
b *= 255
return [r,g,b]
rgb2hsv = (r,g,b) ->
# rgb to hsv
r = r / 255
g = g / 255
b = b / 255
max_v = Math.max(Math.max(r,g), b)
min_v = Math.min(Math.min(r,g), b)
v = max_v
s = max_v - min_v
if min_v == max_v
h = -1
else if min_v == b
h = 60 * (g-r)/s + 60
else if min_v == r
h = 60 * (b-g)/s + 180
else
h = 60 * (r-b)/s + 300
return [h,s,v]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment