Skip to content

Instantly share code, notes, and snippets.

@i-e-b
Created May 21, 2012 22:27
Show Gist options
  • Save i-e-b/2765093 to your computer and use it in GitHub Desktop.
Save i-e-b/2765093 to your computer and use it in GitHub Desktop.
Html5 animation in canvas with coffeescript
class Entity
constructor: (@context, @cw, @ch) ->
# any setup here...
update: ->
# do per-frame updates
draw: ->
# draw using '@context'
@context.fillStyle = 'rgba(0,128,255,0.8)'
@context.fillRect 0,0, @cw, @ch
class DrawingFramework
main: ->
@createCanvas()
@addKeyObservers()
@mainLoop()
mainLoop: ->
@entities = []
@entities.push(new Entity @context, @canvas.width, @canvas.height)
# ... any other things to update and render ...
@runLoop()
runLoop: ->
setTimeout =>
# Adjust for player key input etc before updating...
# Update position of entities
@entities.forEach (e) -> e.update()
# post-update checks, e.g. for collisions
# Clear the Canvas ready for drawing
@clearCanvas()
# Redraw game entities
@entities.forEach (e) -> e.draw()
# Run again unless terminate flag is set
@runLoop() unless @terminateRunLoop
, 20
# Run when the game is quit to clean up everything we create
cleanup: ->
@terminateRunLoop = true
@clearCanvas()
# Creates an overlay for the sceen and a canvas to draw the game on
createCanvas: ->
@canvas = document.getElementById 'canvas'
@context = @canvas.getContext '2d'
# uncomment for fixed size:
#@canvas.width = 640
#@canvas.height = 400
clearCanvas: ->
@context.clearRect 0, 0, @canvas.width, @canvas.height
addKeyObservers: ->
document.addEventListener 'keydown', (e) =>
switch e.keyCode
when 40 then @downPressed = true
when 38 then @upPressed = true
when 90 then @zPressed = true
when 65 then @aPressed = true
, false
document.addEventListener 'keyup', (e) =>
switch e.keyCode
when 27 then @cleanup()
when 40 then @downPressed = false
when 38 then @upPressed = false
when 90 then @zPressed = false
when 65 then @aPressed = false
, false
app = new DrawingFramework
app.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment