Created
November 2, 2011 21:17
-
-
Save lynaghk/1334952 to your computer and use it in GitHub Desktop.
<canvas> gradient generator
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
# print to console for debugging | |
p = (x) -> | |
console.log x | |
x | |
# generate HSL object from normalized arguments | |
hsl = (hue, saturation, lightness) -> | |
h: hue | |
s: saturation | |
l: lightness | |
str: "hsl(#{hue*360}, #{saturation*100}%, #{lightness*100}%)" | |
random_color = -> hsl Math.random(), 1, 0.5 | |
width = 500 | |
height = 500 | |
$c = $("<canvas>", {width: width, height: height}) | |
.appendTo("body") | |
.css | |
border: "2px solid black" | |
margin: "2em" | |
draw_gradient = (color1, color2) -> | |
c = $c[0].getContext("2d") | |
# Interpolation ranges between the two colors. | |
# Unlike R, G, and B, H, S, and L are basically orthogonal in human perceptual space. | |
[dh, ds, dl] = ["h", "s", "l"].map (x) -> color1[x] - color2[x] | |
# Draw from the top | |
[0..(height-1)].forEach (i) -> | |
p = i/height #interpolation / normalized pathlength param | |
c.fillStyle = hsl(color1.h + dh*p, color1.s + ds*p, color1.l + dl*p).str | |
c.fillRect 0, i, width, 1 | |
$('body').append $('<button>') | |
.text("random gradient") | |
.click(-> draw_gradient random_color(), random_color()) | |
.click() #automatically run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment