Edit on Github

2D Graphics

It's pretty easy to get Crafty to display a simple square. (In a full game you'd likely want to use sprites instead of squares, but they're still great for prototyping, so we'll keep using them in these examples.)

Crafty.init(400, 400);
var square = Crafty.e('2D, Canvas, Color');
square.attr({
  x: 10,
  y: 10,
  w: 100,
  h: 100
}).color('red');

What's going on here?

  • First we start Crafty with a stage that is 400 pixels wide and high.
  • Then we create an entity with three components: "2D, Canvas, Color". Anything you want to display will need both the "2D" component and a specific rendering layer; here it's set to use the "Canvas" layer. The "Color" component is responsible for actually drawing a coloured square.
  • Finally we use the .attr() function to set several properties of the entity, in this case its position and dimensions. Like most functions, attr() returns the entity it was called on, so we can chain the color() method to set the color of the entity.

Easy enough! Now we have a red box showing up on the page, but how about setting it into motion? For instance, we might want to set the box spinning; if you look at the documentation for "2D", you'll see that it provides a rotation property, but how could we animate that? Simple enough: we can bind to the "UpdateFrame" event to change the rotation once per frame:

square.bind('UpdateFrame', function(){
  this.rotation = this.rotation + 1;
});

Now we have bound to "UpdateFrame" event, this will be triggered each frame, so the square will rotate.

Now, by default this will rotate about the top left corner, but you'd probably like it to rotate about its center. We can set the origin of the rotation (this is a method provided by "2D"):

square.origin("center")

So putting it all together, the final code would be:

Crafty.init(400, 400);

var square = Crafty.e('2D, Canvas, Color');
square.attr({
  x: 10,
  y: 10,
  w: 100,
  h: 100
}).color('red');

square.origin("center")

square.bind('UpdateFrame', function(){
  this.rotation = this.rotation + 1;
});

And here's the code in action!

JS Bin

The script is editable; try making the square move to the right by adding the code this.x = this.x+1; in the bound "UpdateFrame" function.