Creating game creation tools using HTML5: Setting up the EaselJS canvas

As we saw in the last part, our application is made up of a single view composed of 3 child views.  In this post I am going to focus on the left hand view, which is where the actual map will be drawn.  This is easily the most important part.

 

All I hoped to accomplish today was to get an EaselJS stage integrated in to a YUI View, which with some horrific hacking, I have accomplished.  There are a few very important requirements.

 

First, we need to have a canvas element that EaselJS can work with.

Second, we want the canvas element to take up as much room on the UI as possible.  The right hand view is going to be fixed at 280 pixels in width, so we want the map editing area to consume the rest of the screen.

Finally, I want the whole thing to resize if the window is resized, so our application can support any resolution.

 

To accomplish this, I have altered the person.Template ( the right hand side placeholder for now ), to look like this:

<div style="width:280px;min-width:280px;max-width: 280px;float:right">      <div align=right>          <img src="https://www.gamefromscratch.com/image.axd?picture=HTML-5-RPG_thumb_1.png"                alt="GameFromScratch HTML5 RPG logo" />      </div>      <p><hr /></p>      <div>          <h2>About {{name}}:</h2>          <ul>              <li>{{name}} is {{height}} feet tall and {{age}} years of age.</li>          </ul>      </div>  </div>

Only real change here is the alteration to the parent div.

 

In editor.View.js I made the following simple change that the bottom of the render() function:

Y.one('body').setStyle("margin",0);  return this;

This is simply overriding the YUI default BODY styling, as I do not want any margins, padding or spaces between elements.

 

Then I altered map.Template as follows:

<div style="margin:0px;float:left;display:block" id="panel">      <canvas width=300 height=300 id="mainCanvas" style="background-color: black;">          Your browser doesn't support the canvas tag.      </canvas>  </div>

I needed a named div to access programmatically, so I created one called “panel”.  I also changed the styling on the canvas so the background color would be black, making debugging a bit easier.  The dimensions passed to the canvas are going to be completely ignored.  Why the heck Canvas didn’t support % layout, I will never understand.

 

Finally, the majority of changes are in map.View.js, which I basically re-wrote:

YUI.add('mapView',function(Y){      var Instance = null;      Y.MapView = Y.Base.create('mapView', Y.View, [], {          events:{            "#mainCanvas": {                click:function(e)                {                    alert("Blah");                }            }          },          initializer:function(){              Instance = this;              var results = Y.io('/scripts/views/templates/map.Template',{"sync":true});              template = Y.Handlebars.compile(results.responseText);          },          prepareCanvas:function(){              this.resizeEvent();              createjs.Ticker.setFPS(30);              createjs.Ticker.addListener(this.gameloop);                Y.on('windowresize',this.resizeEvent);          },          render:function(){              if(this.template === null)                  this.initializer();              this.get('container').setHTML(template());              this.prepareCanvas();              return this;          },          gameloop:function(){              Instance.stage.update();              Instance.stage.getChildAt(0).x++;              if(Instance.stage.getChildAt(0).x > Instance.stage.canvas.width)                  Instance.stage.getChildAt(0).x = 0;          },          resizeEvent:function(){              var container = Instance.get('container');              var canvas = container.one("#mainCanvas");              var panel = container.one('#panel');                var body = Y.one("body");              var screenWidth = body.get("clientWidth");              var screenHeight = body.get("scrollHeight");                var width = Math.floor(screenWidth -280);              var height = Math.floor(screenHeight );                canvas.setStyle("width",width);              canvas.setStyle("height",height);                this.stage = new createjs.Stage(canvas.getDOMNode());              // for some reason, easel doesn't pick up our updated canvas size so set it manually              this.stage.canvas.width = width;              this.stage.canvas.height = height;                var shape1 = new createjs.Shape();              shape1.graphics.beginFill(createjs.Graphics.getRGB(0,255,0));              shape1.graphics.drawCircle(200,200,200);                this.stage.addChild(shape1);          }      });  }, '0.0.1', { requires: ['view','event','io-base','handlebars']});

 

The variable Instance is a horrible hack, that I intend to replace at some point in the future.  That’s the joy of exercises like this, I can refactor out my hacks later on.  So, why does it exist… well you see, I make a couple of functions that are called back by external code, which completely clobber my this pointer.  I suppose it’s a poor mans singleton of sorts.

 

The end result of this code:

 

 

First thing I did within MapView is declare an event if someone clicks on our canvas ( which needs the id mainCanvas… this is another hackish solution that should possibly be factored away, although frankly, I am OK with requiring the canvas tag to have a certain ID, so I probably wont ) this function is called.  It was simply written to figure out how YUI views handled events.  All it does is pops up an alert with the text Blah.  As you can see, handling element level events in relatively simple, although sadly I couldn’t figure out how to capture document level events here.  Another thing on the todo list.

 

In the initializer function I take a copy of the this pointer in the Instance variable ( *hack* *hack* ), and have changed the template fetching code to no longer be asynchronous, to completely remove some unnecessary race conditions that can result from a network delay retrieving the template. Frankly in this case, async bought us nothing but headaches.

 

prepareCanvas is the method responsible for setting up the easelJS integration.  It starts off by calling resizeEvents, which is where the bulk of the actual work is done.  resizeEvents was factored out to a separate function, because this logic is the same on initial creation as it is when the window is resized.  When resizeEvent() is called, we first find the BODY tag, and get its width and height using clientWidth and scrollHeight.  You would think the obvious value would be clientHeight, but you would be wrong, this is just one of those ways that HTML sucks.  Once we have the width and height, we then calculate our view dimensions, by subtracting the space needed for the other views ( or… will soon for height that is ).  We then set the canvas to those dimensions using setStyle(), which resizes the CANVAS in the browser.  We then create our Stage object from our canvas.  One thing to keep in mind, YUI get() and one() functions return YUI Node objects, not actual DOM objects, so when dealing with 3rd party libraries, you need to access the actual DOM item the node contains, that can be done with .getDOMNode().  Next we manually update the stage.canvas width and height, because of what I can only assume is a bug, EaselJS doesn’t pick up the modifications we made to the Canvas dimenions… who knows, there might be something else going on behind the scenes.  Next we create a circle… just so we have something visible on screen, and add it to our stage.

 

Now that resizeEvents is done, back in prepareCanvas we then set up a Ticker, which is an EaselJS callback mechanism, somewhat like setTimeout.  This is the heartbeat of your application, and due to the setFPS(30) call, it *should* be called 30 times per second.  This is your traditional game loop within the application and will probably be used quite a bit in the future.  Finally we handle windowresize events using the Y.on() handling mechanism, to catch the case the user resizes the screen, and if they do we call resizeEvents ( which being an eventhandler, will clobber all over our this pointer ).

 

Finally, we have the aforementioned gameloop, which is a function that is going to be called every time createjs.Ticker, um… Ticks.  For now we simply update our stage, then find the one and only item on our stage with getChildAt(0), which is our circle, and increment it’s X value until it scrolls off the screen.

 

It seems a bit more complicated than it is, but the basics of most of what we are going to want to deal with is now in place.  We can handle UI events via YUI, can render to the Canvas using the EaselJS library and best of all, take full advantage of the screen resolution, no matter how big or small, and gracefully handle changes in size, something Canvas doesn’t do easily.

 

Figuring out how everything interacted was more of a headache than I expected, but I am reasonably happy with this setup for now.  Of coure, I am going to need to add real functionality to the map view, and have it feed by a Map model instead of just drawing a circle on screen, but all things in time.

 

You can download the complete project as of this point right here.

You can see the project in action by clicking here.  As you resize, so will the canvas element.

Programming Design YUI Design


Scroll to Top