class Entity
width: 0
height: 0
x: 0
y: 0
children: []
parent: null
constructor: (@width, @height) ->
# Create the canvas we will be rendering the object to
@canvas = document.createElement('canvas')
@canvas.width = @width
@canvas.height = @height
# Call this function to render out the object, returns a Canvas instance
render: ->
ctx = @canvas.getContext('2d')
# Clear the canvas, important for animation
ctx.clearRect(0, 0, @width, @height)
@draw(ctx)
@canvas # return the canvas
draw: (ctx) ->
for child in @children
ctx.drawImage(child.render(), child.x, child.y)
false # return some value, otherwise CoffeeScript will return an array
# Usage
# =====
scene = new Entity(400, 400)
document.body.appendChild(scene.canvas)
box_draw = (ctx) ->
ctx.fillRect(0,0,30,30)
box = new Entity(30, 30)
box.draw = box_draw
box1 = new Entity(30, 30)
box1.draw = box_draw
box2 = new Entity(30, 30)
box2.draw = box_draw
agregation = new Entity(100, 100)
agregation.children = [box1, box2]
box1.x = 30
box2.x = 60
box2.y = 40
# notice that these two boxes start at the bottom, since their parent is at the bottom
agregation.x = 300
agregation.y = 300
scene.children = [box, agregation]
# Animation loop
window.setInterval( ->
box.x += 0.5
box.y += 0.4
box1.y += 0.1
agregation.y -= 0.8
scene.render()
, 60)