Skip to content

Instantly share code, notes, and snippets.

@darthtrevino
Created September 10, 2011 08:36
Show Gist options
  • Save darthtrevino/1208119 to your computer and use it in GitHub Desktop.
Save darthtrevino/1208119 to your computer and use it in GitHub Desktop.
CoffeeScript chained lambdas for aop-based drawing
ctx = $('#canvas')[0].getContext("2d")
palette = {Gray:'#E8E8E8', Black:'#000000'}
point = (xVal, yVal) -> {x: xVal, y: yVal}
line = (from, to) ->
ctx.moveTo(from.x, from.y)
ctx.lineTo(to.x, to.y)
ctx.stroke()
class Chain
constructor: ->
@chain = []
this
addLink: (func) =>
@chain[@chain.length] = func
this
invoke: (func) =>
i = 0
invokeNext = () =>
if i < @chain.length
@chain[i++](() -> invokeNext())
else
func()
invokeNext()
class Path extends Chain
constructor: ->
super
this.addLink((inner) ->
ctx.beginPath()
inner()
ctx.closePath())
withStroke: (color) =>
this.addLink((inner) ->
old = ctx.strokeStyle
ctx.strokeStyle = color
inner()
ctx.strokeStyle = old)
draw: (func) =>
this.invoke(func)
#######
# Fire off the Chain!
new Path().withStroke(palette.Gray).draw(() ->
line(point(0,0), point(100, 100))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment