CoffeeScript & Kinetic.js

Simple example of using coffeescript with kinetic.js

by evaneus

HTML

<script src="http://www.kineticjs.com/download/kinetic-v3.9.5.js"></script>
<!DOCTYPE HTML>
<html>
  <head>
    <style>
      #container {
        background-image: url('http://www.html5canvastutorials.com/demos/assets/blue-background.jpg');
        height: 200px;
        width: 530px;
      }
    </style>
 
  </head>

<body onmousedown="return false;">

<div id="container"></div>
    
<input type="button" id="tango" value="Tango!">

</body>
</html>

CoffeeScript

# Simple Coffeescript Example
# Taken from http://coffeequery.blogspot.com/2012/04/kineticjs-kaleidoscope-tango.html
#


# bind jQuery to $
$ = jQuery

colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']

containerWidth = $('#container').width()
containerHeight = $('#container').height()

# Add polygons to a layer
addPolygon = (layer) ->
    n = layer.getChildren().length + 1
    layer.add new Kinetic.RegularPolygon
        fill: colors[n % colors.length]
        # As the first n is 1, the first poly is a triangle
        sides: n + 2
        draggable: true
        x: (n % 10+1) * 50
        y: (n % 3 + 1) * 50
        radius: 40
        strokeWidth: 4

$ ->
  # Get a named div sized appropriately, 
  # then create a Kinetic Stage, 
  # then fill it with some shapes:
  stage = new Kinetic.Stage
    container: 'container'
    width: containerWidth
    height: containerHeight
  layer = new Kinetic.Layer()
  stage.add layer

  $('#tango').click ->
    addPolygon layer
    stage.add layer