Created
April 27, 2012 21:36
-
-
Save issa-tseng/2513472 to your computer and use it in GitHub Desktop.
color.coffee
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# color.coffee - triple rainbow | |
# thanks wikipedia! | |
color = | |
rgbToHsl: (red, green, blue) -> | |
red /= 255 | |
green /= 255 | |
blue /= 255 | |
max = Math.max(red, green, blue) | |
min = Math.min(red, green, blue) | |
hue = 0 | |
sat = 0 | |
lum = (max + min) / 2 | |
if max != min | |
chroma = max - min | |
sat = | |
if lum > 0.5 | |
chroma / (2 - chroma) | |
else | |
chroma / (max + min) | |
hue = | |
if max == red then ((green - blue) / chroma) % 6 | |
else if max == green then (blue - red) / chroma + 2 | |
else if max == blue then (red - green) / chroma + 4 | |
[ Math.floor(hue * 60), Math.floor(sat * 100), Math.floor(lum * 100) ] | |
hslToRgb: (hue, sat, lum) -> | |
sat /= 100 | |
lum /= 100 | |
chroma = (1 - Math.abs(2 * lum - 1)) * sat | |
hueProj = hue / 60 | |
chroma2 = chroma * (1 - Math.abs((hueProj % 2) - 1)) | |
[red, green, blue] = | |
if hueProj < 1 then [ chroma, chroma2, 0 ] | |
else if hueProj < 2 then [ chroma2, chroma, 0 ] | |
else if hueProj < 3 then [ 0, chroma, chroma2 ] | |
else if hueProj < 4 then [ 0, chroma2, chroma ] | |
else if hueProj < 5 then [ chroma2, 0, chroma ] | |
else if hueProj < 6 then [ chroma, 0, chroma2 ] | |
lumDiff = lum - 0.5 * chroma | |
Math.floor((component + lumDiff) * 255) for component in [ red, green, blue ] | |
lerp: ([ red1, green1, blue1 ], [ red2, green2, blue2 ], steps) -> | |
[ hue1, sat1, lum1 ] = color.rgbToHsl(red1, green1, blue1) | |
[ hue2, sat2, lum2 ] = color.rgbToHsl(red2, green2, blue2) | |
hueStep = (hue2 - hue1) / steps | |
satStep = (sat2 - sat1) / steps | |
lumStep = (lum2 - lum1) / steps | |
console.log('hueStep: ' + hueStep) | |
for step in [0..steps] | |
color.hslToRgb(hue1 + hueStep * step, | |
sat1 + satStep * step, | |
lum1 + lumStep * step) | |
(exports ? this).color = color |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment