Skip to content

Instantly share code, notes, and snippets.

@samccone
Created June 12, 2012 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samccone/2918163 to your computer and use it in GitHub Desktop.
Save samccone/2918163 to your computer and use it in GitHub Desktop.
fixing newb problems
window.onload = ->
img = new Image()
img.src = '600.jpeg'
img.onload = ->
el = document.getElementById('stage')
ctx = el.getContext('2d')
el.setAttribute 'width', img.width
el.setAttribute 'height', img.height
ctx.drawImage img, 0, 0
width = img.width
height = img.height
img_data = ctx.getImageData(0, 0, width, height)
# color conversion and processing functions
hue_to_rgb = (m1, m2, h) ->
h += 1 if h < 0
h -= 1 if h > 1
return m1 + (m2 - m1) * h * 6 if h * 6 < 1
return m2 if h * 2 < 1
return m1 + (m2 - m1) * (2.0/3 - h) * 6 if h * 3 < 2
return m1
rgb_to_hsl = (rgbin) ->
rgb = []
for val in rgbin
rgb.push val/255.0
max = Math.max.apply(Math, rgb)
min = Math.min.apply(Math, rgb)
diff = max - min
h = switch max
when min then 0
when rgb[0] then 60 * (rgb[1]-rgb[2]) / diff
when rgb[1] then 60 * (rgb[2]-rgb[0]) / diff + 120
when rgb[2] then 60 * (rgb[0]-rgb[1]) / diff + 240
l = (max + min) / 2.0
s = if max == min
0
else if l < 0.5
diff / (2 * l)
else
diff / (2 - 2 * l)
[h % 360, s * 100, l * 100]
hsl_to_rgb = (hsl) ->
h = hsl[0] / 360.0
s = hsl[1] / 100.0
l = hsl[2] / 100.0
m2 = if l <= 0.5 then l * (s + 1) else l + s - l * s
m1 = l * 2 - m2
rgb = []
rgb[0] = Math.round(hue_to_rgb(m1, m2, h + 1.0/3) * 0xff)
rgb[1] = Math.round(hue_to_rgb(m1, m2, h) * 0xff)
rgb[2] = Math.round(hue_to_rgb(m1, m2, h - 1.0/3) * 0xff)
return rgb
# return the rgba value of the pixel at x, y
get_pixel = (x, y, type) ->
index = (x + y * img_data.width) * 4
if type == 'rgb'
[img_data.data[index], img_data.data[index + 1], img_data.data[index + 2]]
else
[img_data.data[index], img_data.data[index + 1], img_data.data[index + 2], img_data.data[index + 3]]
# set pixel at x, y to the rgba array passed in
set_pixel = (x, y, color) ->
index = (x + y * img_data.width) * 4
for x in [0..3]
img_data.data[index + x] = color[x]
lighten = (x, y, amount) ->
pixel_color = get_pixel(x, y, 'rgb')
pixel_color[0] = Math.min 255, pixel_color[0] + amount
pixel_color[1] = Math.min 255, pixel_color[1] + amount
pixel_color[2] = Math.min 255, pixel_color[2] + amount
pixel_color[3] = 255 # can't yet handle alpha
set_pixel(x, y, pixel_color)
desaturate = (x, y, percent) ->
saturate = (x, y, percent) ->
darken = (x, y, percent) ->
for x in [0..img_data.width]
for y in [0..img_data.height]
lighten x, y, 255 * .1
ctx.putImageData img_data, 0, 0 # re-render the image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment