Introduction to CraftyJS : Initilization ( DOM vs Canvas)

  • Crafty is a JavaScript game engine to help you develop games for the browser (and not just the new ones). With a modular design,using reusable components.
  • First you need to grab the latest release of the crafty engine.(
  • To make a Crafty Game work in the Browser, you need an HTML file that loads the JavaScript. In its most simple form it will look like this:
<!DOCTYPE html>
<title>My Awesome Game</title>
<script src="jquery-1.8.2.js" type="text/javascript"></script>
<script src="crafty.js" type="text/javascript"></script>
<script src="gameEntityComponent.js" type="text/javascript"></script>

  • jquery-1.8.2.js is the javaScript file for jQuery framework.
  • crafty.js is the downloaded javaScript for crafty.
  • game.js is our javaScript file for game.

Our game.js file will look something like this :

// When the DOM has loaded
$(document).ready(function() {// Height and Width
var WIDTH = 800, HEIGHT = 640;

// Initialize Crafty
Crafty.init(WIDTH, HEIGHT);

// Background

  • We want the code to be executed when the page loads, which is done by wrapping the game in $(document).ready function of jQuery.
  • Crafty.init(width, height) is where Crafty does it’s initialization stuff that is needed before the game can run.
  • There are two ways of getting images onto the screen:
    • Using a canvas element that is like a big square of screen estate that you get to draw pixels on or
    • using normal DOM elements that you can manipulate using css and javascript but is drawn to the screen by the browser.
  • It turns out that the DOM method is fastest in most cases.
  • If we want to use canvas you need to call Crafty.canvas.init() like below :
// When the DOM has loaded
$(document).ready(function() {

//Height and Width
 var WIDTH = 800, HEIGHT = 640;

// Initialize Crafty
 Crafty.init(WIDTH, HEIGHT);


  • Crafty abstracts away most differences between DOM and canvas, so it is a matter of changing a single variable if you decide to change later.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s