Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon
30. January 2013

 

Don’t you just love it when you are thinking about doing something, then someone else comes along and does exactly that thing for you?  Well, exactly just that very thing just happened to me.  I had long considered doing a comparison post of some of the most popular HTML5 game engines, facing them all against each other implementing a common game and see which one came out on top.

 

Well, BuildNewGames.com just did exactly that.  In their words:

Today we are going to compare three popular JavaScript game engines: CraftyJS, ImpactJS and LimeJS. You really can’t go wrong with any of these great choices, but they do have their own strengths, weaknesses and style. Taking some time to get to know what’s out there is well worth it before embarking on a game

 

Most interestingly, he followed in the vein of popular TodoMVC example, of implementing a standard application to give you a quick glance at each framework in action.  The author has implemented a Breakout clone using each library.  Like so:

breakout screenshot

 

This is a very useful exercise, and I hope others pick up the baton and implement the same program in their framework of choice. 

 

In the end, ( spoiler alert ), the author comes to the follow conclusion:

So which engine is the real winner? I will leave that to you to decide. Since Lime and Crafty are free and open source, it’s easy to dive into them and give them a whirl. Impact is at a disadvantage here, as you need to pony up for the license before you can start playing with it. It’d be nice if Impact had some sort of trial period option.

 

If you are trying to select a JavaScript game engine, this is certainly a great read.

News Programming


7. December 2012

 

Yesterday the cocos2d community announced the first coordinated release of the cocos2d products.  What products comprise this family?

 

  • CocosBuilder v3.0-alpha0
  • cocos2d-html5 v2.1
  • cocos2d-iphone v2.1-beta4
  • cocos2d-x v2.1beta3-x–2.1.0

 

So what is the relationship between these products?  Well, this gets a bit confusing…  cocos2d is the original library, an Objective-C port of the original cocos2D Python library.  cocos2d-x is the C++ port of this library.  cocos2d-html5 is the JavaScript (HTML5) port, while CocosBuilder is… well, its new.

 

 

CocosBuilder is, in their own words:

 

CocosBuilder is a free tool (released under MIT-licence) for rapidly developing games and apps. CocosBuilder is built for Cocos2d’s Javascript bindings, which means that your code, animations, and interfaces will run unmodified on iPhone, Android and HTML 5. If you prefer to go native all the way, there are readers available for cocos2d-iphone and cocos2d-x.

Testing your game on a mobile device has never been quicker or easier, just install CocosPlayer on your device (or in Simulator) and CocosBuilder will push your code over wifi in just a few seconds. Hit the publish button and your game will be saved instantly to a html5 web page. CocosBuilder has a rich set of functions, including boned animations, nestling of interface files, support for multiple resolutions and automatic scaling of your assets.

 

 

Basically, they’ve bundled all the various products together into a standardized release.  I’ve not had a chance to sit down with CocosBuilder, but it sounds like a cool idea.  We have a number of Cocos2D HTML tutorials on this site if you are interested in seeing a cocos2D application in action.

News


9. November 2012

I recently hosted a guest tutorial post on using Moscrif, a new Javascript based cross platform, game focused development environment.  Thing is, I myself haven't really had a chance to check out Moscrif myself.  In the past I did try out a Moscrif Logosimilar environment Appcelerator Titanium, which for a couple of reasons, I chose not to keep using, many of which aren't actually Appcelerator's fault (the no other word for it, complete crap Android emulator, was the biggest drawback). 

 

Moscrif on the other hand is a bit different.  Like Appcelerator, it's cross platform, mobile focused, JavaScript based and comes with it's own IDE.  Unlike Appcelerator it ships with a simulator you can use for stage 1 debugging, removing the biggest headache.  Perhaps most important of all for readers of this site, Moscrif is also game focused while Titanium is not ( yet ).

 

So, I've decided to take a bit closer look at Moscrif, over a couple of posts.  First off, this is *not* a review.  I certainly haven't put enough time in with Moscrif to even consider reviewing it.  Consider it instead a tour of features available as well as my initial impressions.

 

So, what then is Moscrif anyways?

The above description is pretty much accurate.  Moscrif is a cross platform JavaScript based IDE/language/library for creating mobile applications with a focus on games.  If you've ever used Appcelerator Titanium, you've got a pretty good idea of what you are getting here, just with a more game oriented focus.  The tools run on Windows, Mac and Linux, while you can target iOS, Android and oddly enough… Bada, with a single code base.

 

Installation process

Moscrif install was easy enough, but theres a catch.  You need to create an account (which you can do here), and like the Corona SDK and Appcelerator, you will need to log in to do anything, making an always on connection pretty much a much.  Unfortunately this login process is required even if you are just using the basic version.

Otherwise the install process is pretty much a no-brainer.  In my case I am using Mac OS.  You simply download the package and run a pair of installs.  Moscrif depends on a particular version of the Mono framework, which you need to install first.  It is included in the downloaded package, so simply download, run the Mono installer then the Moscrif installer, that's about it.  You can download (and register) right here.

Once you've finished installing, the first time you run Moscrif you will have to log in with your Moscif account.

 

A first look at the IDE

Load up and log in to Moscrif and you will be greeted by the screen:

IDE Screenshot

 

As you can see, it's a pretty complete and traditional IDE.  Your project management window is on the left, your console and debug windows are across the bottom and the remains of the window is for code editing.  You can use the icons at the top right to toggle sections of the IDE on and off.  I do have one immediate annoyance though, I am running on MacOS and there is no ability to maximize the window, or whatever that feature is called.  Considering that single feature is what makes Mac tolerable to me, hopefully support is added soon!

 

Hello World

To get a feel for the application, let's create an extremely simple Hello World project.

To get started, select File->New->New Project.

In the resulting dialog, choose 2D Game and name your project, I went with Hello World. Like so:

NewImage

 

Now in the next dialog, keep Game2D selected and choose Finish.

NewImage

It will have created a project for you like the one pictured to the left.

 

Main.ms is the file we are most interest in, it is the main entry point of your project.

 

 

 

 

 

 

 

 

Now replace the code in main.ms with the following:

include "lib://game2d/game.ms"

 

class HelloWorld : Game {

    function start()

    {

        super.start();

        this.paint = new Paint();

        this.paint.textSize = 72;

    }

 

    function draw(canvas)

    {

        canvas.clear(0xffffffff);

        canvas.color = 0x000000ff;

        var (w,h) = this.paint.measureText("Hello world")

 

        canvas.drawText("Hello world",System.width/2 -w/2,System.height/2 -h/2, this.paint);

    }

 

}

 

new HelloWorld().run();

 

As you can see, Moscrif is very similar to JavaScript with some obvious extensions, such as class or multiple return values.

Now let's run our new application, which brings us to...

 

The Simulator

Across the top of our screen are the simulator controls:

NewImage

 

Simply click Run, and the iPhone4 simulator will run.  Voila:

NewImage

 

You can control the Simulator with the following hotkeys, although the rotation keys don't work if you don't support landscape changes in code.  I also had a bit of a fight getting F11 and F12 working on Mac, but that is more an OS issue than a Moscrif issue.

 

Operation Mac OS Linux Windows Moscrif symbol
Take screenshot F12 coming soon F12  
Rotate left F11 F11  
Rotate right F11 F11  
Left functional key F1 F1 #left
Right functional key F2 F2 #right
Send / Green / Talk F3 F3 #send
End / Red F4 F4 #end
Back Backspace Backspace #back
Ok / Centre key / Confirm Return Return #ok
Volume Up F6   #volumeUp
Volume Down F7   #volumeDown
Camera F5   #camera
Power     #power
Menu F8   #menu
Home F9   #home
Zoom In Cmd + (=) Ctrl I, Ctrl +  
Zoom Out Cms - Ctrl O, Ctrl -  

 

As you can see from the display options, there is a decent number of profiles pre-configured.

NewImage

 

I did run in to a few issues, when I switched from Iphone3 to iPad, then implemented screen rotation, only a 480x320 portion of the screen was rendered.  That said, having a simulator layer massively improves turn around time, especially when working on Android where the emulator is pure garbage.

 

Publishing

The simulator is nice, but at the end of the day you are going to want to run on an actual device.  That process is actually quite simple.

Simply select the menu Project->Publish

The following dialog will appear:

Publish Dialog

 

 

Select your OS as a tab at the top, click a checkbox beside a skin and click the Publish button.  You can totally tell a programmer wrote this dialog… Reset Matrix?  Really? ;)  Coincidentally Reset Matrix is simply De-select, if you are curious.

After clicking Publish, Moscrif will churn away for a little bit and a Finder/Explorer window will pop up with your APK file ready for deployment.  I have to admit, this process is quite impressive, as it doesn't require you to install the Android tools, mess with any environment variables or any of the typical fun.  If you are just starting out, this is about the easiest way to generate an APK file I've ever seen.  Coincidentally, the APK was about 4MB in size, which is pretty impressive.  When using Titanium, a Hello World measured in closer to 10MB.

There is however a downside (one Appcelerator Titanium shares), you can't currently debug on device, which sucks.  You can log/trace back to the IDE as your program runs, but that's it. There are a whole class of bugs, especially on Android, that only express themselves on an actual device, so this can get a bit annoying.  Let's hope the simulator does a very good job of, well, Simulating.  Fortunately, on device debugging is a very near term item on the roadmap of features.  Even more confusing, it doesn't appear you can debug in the simulator either, other than debug logging.  I have become so used to being able to set breakpoints and step through code, it feels like a major omission when I cant. Hopefully this functionality gets added, at least to the simulator. Or perhaps I simply overlooked the functionality somewhere.

 

Other stuff and closing thoughts

The IDE is fairly easy to come to terms with.  What you see is pretty much what you get, there aren't a hundred menu items or nested dialogs, and there really doesn't have to be.  The code editing tools are pretty impressive, with good legible errors displayed in realtime.  There is code completion, it's quick and appears to work exactly as you would expect it to. Otherwise it's a fairly barebones but functional code editor.  There is smart tabbing, find/replace, code suggestions/completion, hover-over code tips and code folding and thats about it. For more advanced editing, such as refactoring, you need to move to a more dedicated text editor.  Truth is, in 99% of occasions, the IDE is a perfectly capable and even enjoyable place to edit your code.

Next is the area of support and community.  Let me start with the bad, community.  I am not saying the community is bad, more… missing.  One of the downsides of being a fairly new product is the lack of information online.  When you run in to a problem on Moscrif, there isn't yet a large community to turn to and Google won't come to save you.

Now, the good.  Moscrif's documentation ROCKS.  It staggers me how good of a job they have done.  Theres a pretty good step by step documentation that walk you through many of the features with code examples.  Where Moscrif really shines though is the reference materials. It's comprehensive, complete, timely and almost always comes with a code sample.  The reference material goes a long way to minimizing the lack of community…  you don't have as many people out there to answer your questions… but you have such great documentation that you don't really have any questions in the first place!  If you are middleware publisher and want to know how to do documentation… look no further!

I haven't really gotten the chance to really dive in and code.  That said, what I saw in my initial inspection certainly have my interest piqued, so I will be looking at the code side of things shortly.  So stay tuned for a more detailed hands on with the code in the future.  I am impressed by what I've seen so far.

 

Pros

  • it's JavaScript based
  • no external dependencies. No need to install other tools or SDKs. Fastest way I've seen to build an Android app yet
  • small executable size for the type of tool it is
  • EXCELLENT reference materials
  • all in one, easy to get started, reasonably complete
  • simulator makes for fast dev turn around times
  • JavaScript language enhancements that fix some of JavaScript's warts
  • Fast OpenGL based performance

Cons

  • it's JavaScript based 
  • lack of online presence, forum software is terrible and finding information not in the documentation is difficult
  • internet connection required
  • debugger needs improvement and basic debugging features ( breakpoints, inspection, etc ) added
  • it's young and relatively unproven 

 

Stay tuned for a later post when I look at Moscrif from a coding perspective.

 

General Programming


14. October 2012

 

I don’t think there are many people out there that would argue that JavaScript isn’t an important language.  It certainly is, and with the recent death of Flash and Silverlight in the browser and the hype behind HTML5, to say nothing of Node, it is actually getting more popular

 

I also don’t think there are many people out there that would argue that JavaScript is a heavily broken language too.  As systems written in JavaScript become larger and more complex, the language flaws become more and more pronounced.  Just as C++ ultimately came about from C’s (arguable by some) inability to deal with complexity, a number of companies and groups are looking at possible successors to JavaScript.  Generally all of these languages are backward compatible with JavaScript in some form.  Let’s take a look at the contenders for the short term future of JavaScript.

 

 

ECMAScript 6 AKA Harmony AKA ES.next

 

When talking about the future of JavaScript, the most logical place to start is … well, the future of JavaScript, the next version.  The spec is a work in progress and you can read it here, the most recent revision as of writing (September 27th, 2012).  It would seem obvious that the next version of JavaScript would be ECMAScript 6, but don’t bet the farm just yet.  After all, ECMAScript 6 is effectively a scaled back version of ECMAScript 4, while ECMAScript 5 (the JavaScript version in common usage today), is essentially a fork of ECMAScript 3.  Firefox and Chrome already support bits of ECMAScript 6, so it’s future is quite bright, but by no means are things certain.  Plus there is no way of knowing how long until ECMAScript 6 is supported enough to actually make it useful.  For an idea of where ECMAScript support in various browsers is, check out this handy table.

 

This has opened the door to a number of alternatives, many are languages that compile down to JavaScript making them useful today. Others (like Dart) compile down to JavaScript as a fallback, but perform better in their native environment.

 

 

The 900lb gorillas.

 

Two of the companies are very interested in the future of JavaScript are Google and Microsoft.  Each has created a language they hope will be the future of JavaScript, Dart and TypeScript respectively.

 

This interview between Anders Hejlsberg ( Microsoft, creator of Delphi, C# and now TypeScript ) and Lars Bak ( Google, creator of V8 JavaScript engine and Dart ) is very good summary.  It allows each developer to describe their opinions of the existing problems with JavaScript ( on which they largely agree ) and describe the strengths of each of their companies offerings.

 

Anders Heljsberg & Lars Bak on TypeScript/Dart and the problems with JavaScript today

 

 

Google Dart

 

http://code.google.com/p/dart/ or http://www.dartlang.org/

image

 

In Their Words:

Why Dart?

At Google we've written our share of web apps, and we've tried in many ways to make improvements to that development process, short of introducing a new language. Now we think it's time to take that leap. We designed Dart to be easy to write development tools for, well-suited to modern app development, and capable of high-performance implementations.

 

Dynamic or Static Typed?

Dynamic

 

Key language features

Compiles down to JavaScript, or to the Dart VM ( which is currently only available in Chrome ).  Code running in the Dart VM will perform better.

Language is basically JavaScript with prototypes removed and classes added.  They’ve added lexical closures, sane this management, optional static types, named parameters, cleaner event and DOM programming and more.

The language also comes with an IDE, the Dart Editor, which is a mash-up of Eclipse, Chromium and the DartVM.  For those like me that prefer WebStorm/IntelliJ over Eclipse, they also have a plugin available.  There used to be a cloud based editor, but it appears to have been retired.

 

My 2 cents

Dart technically solves most of the problems with JavaScript and is compatible with existing JavaScript.  That said, I checked out Dart shortly after it was released, then again 6 months later and as usual, Google’s developer support stunk.  They just don’t put the extra effort in to making the experience easy on developers ( at the time, the Windows build didn’t work, you need to compile everything yourself, etc… this lack of polish is just as common with other Google developer tools such as GWT, NativeClient even Android), but the package seems to be improved quite a bit.  Just a warning though, if you aren’t experienced with Google developer support, be prepared for a ton of frustrations if you run in to any problems.

Probably the biggest flaw with Dart is going to be the lack of adoption.  Dart compiles to JavaScript as a fall back, but the VM is obviously the preferred platform.  Google announced their intention of submitting Dart to a standards body, but do you see Microsoft or Mozilla adopting Dart?  Yeah, me neither.  That said, Chrome is getting a pretty big install base.

My biggest problems are the above mentioned Google support, and their tendency to kill off projects at the drop of a hat lately. 

 

 

Microsoft TypeScript

 

http://www.typescriptlang.org/

 

image

In Their Words:

Why TypeScript?

TypeScript is a language for application-scale JavaScript development. TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. Any browser. Any host. Any OS. Open Source.

Dynamic or Static Typed?

Static

 

Key language features

TypeScript is compiled down to JavaScript.

Language allows you to add static types to JavaScript, allowing you to catch type errors during the compilation process ( although the compilation will still generate a JS file ).  Allows you to mix and match TypeScript and JavaScript in existing files.  Adds new constructs to the language such as classes, interfaces and modules.

IDE support is available in the form of a Visual Studio 2012 plugin, as well as plugins for Sublime Text, Vi and Emacs.  They also have Node support out of the box and you can download TypeScript using NPM.

 

My 2 cents

I will admit, I am a bit of a Anders fanboy, so that has gotten me excited about this language.  Language design is all about pragmatic choices, and Anders just seems to pick the right compromises.

At the end of the day, TypeScript is less of a gamble than Dart, and this has it’s advantages and disadvantages.  As Lars said in that video above, TypeScript is “the safe bet” and that is a pretty apt description.  It is a layer on top of JavaScript and nothing more, in many ways it is quite similar to CoffeeScript.  In the end though, TypeScript is probably the one that will best integrate with existing Javascript and given the massive variety of existing code, that is probably a pretty big advantage.  At the end of the day though, TypeScript is ends up being JavaScript, so don’t expect any performance improvements.

The tooling support is shockingly not Microsoft.  Would you have ever expected Vi and Emacs support from day 1?  What about Node support?  There is a noted lack of documentation at this point, which is shocking for a Microsoft product.  They do however have a nifty Playground/Tutorial environment that allows you to type TypeScript and see the generated JavaScript.  Sadly for now, comments and whitespaces are mangled as part of the process, although this is a temporary flaw.

 

 

CoffeeScript

http://coffeescript.org/

 

In Their Words:

CoffeeScript is a little language that compiles into JavaScript. Underneath all those awkward braces and semicolons, JavaScript has alwaysimage had a gorgeous object model at its heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way.

The golden rule of CoffeeScript is: "It's just JavaScript". The code compiles one-to-one into the equivalent JS, and there is no interpretation at runtime

 

Dynamic or Static Typed?

Dynamic

 

Key Language Features

Coffeescript is a whitespace ( as opposed to curly brace ) based language that compiles down to JavaScript.  It is certainly the elder statements of the group and has been around for a number of years.

Coffeescript provides a number of features to JavaScript including a class system, lexical scoping, splats (…) for variable arguments, array slicing and more.  Additionally it provides a layer of syntactical sugar over some of the JavaScript warts such as is instead of === or unless as the inverse of if.

Coffeescript also offers impressive tooling support.  Like TypeScript, it is available as a Node utility, making installation via NPM trivial.  Most IDEs support Coffeescript ( IntelliJ, Eclipse, WebStorm, Netbeans, Sublime Text, etc ) out of the box.

 

My 2 cents

I only gave CoffeeScript the smallest of evaluations and that was a few years back.  You see, I have an irrational hatred of whitespace based languages.  What I found most irksome ( and TypeScript fixed this ), is that it’s a language on-top of JavaScript, not within Javascript.  So you had to program things the Coffeescript way, then compile it to JavaScript.  Coffeescript felt like a completely different language than JavaScript, while neither Dart nor TypeScript gave me that impression.  Mostly though, I never got over my hatred of whitespace based languages.

All that said, CoffeeScript solved many of the problems that Dart and TypeScript are setting out to solve, and it solved them years ago.  It’s by far the most mature and as a result had the most time to iron out the kinks.

 

 

Other Options

 

Dart, TypeScript and CoffeeScript are by no means the only options when it comes to more programmer friendly JavaScript programming languages, but they are the three that are closest to JavaScript itself.  The following are a selection of other languages that will compile to JavaScript.

 

 

GWT – Google Web Toolkit

 

https://developers.google.com/web-toolkit/

Google Web Toolkit (GWT) is a development toolkit for building and optimizing complex browser-based applications. GWT is used by many products atimage Google, including Google AdWords and Orkut. It's open source, completely free, and used by thousands of developers around the world.

Basically GTW is a Java –> JavaScript compiler.  That is over generalizing, but basically you write your code using a subset of libraries in the Java language, and it is compiled down to JavaScript.  Or a bit of mix and match, with Java running on the server and JavaScript on the client.  The programmer never really works in JavaScript when working with GWT.

 

As is pretty typical with Google projects, IDE support is mostly Eclipse based.  There are a few published books available for GWT.  GWT has been around for quite a while and integrates nicely with Google App Engine.  That said, if you aren’t a Java developer, GWT really isn’t for you.

 

 

 

Haxe

 

http://haxe.org/

Haxe is a powerful modern language with many compelling features. It is aimed at giving developers a tool to create websites & applications using aimage single unified programming language. Whether you use Haxe for its cross-platform features, or focus on a single platform, there are many reasons to adopt it.

Haxe is a language that allows you to compile down to JavaScript, Flash, NekoVM, PHP, C++, C# and Java.  It provides a standard language and library that compiles down to the mentioned languages, while filling in the missing pieces of each language, such as packages and typing for JavaScript, reflection for C++, etc.  The Haxe language itself is derived from ActionScript 3, which itself is a ECMAScript language. Haxe has pretty good IDE support. Haxe also has a few published books which is always handy.

 

I’ve not yet used Haxe, mostly because I have no prior ActionScript experience and because I never really had the time to look into it further. That said, HaxeNME, which is a gaming library targeting web, mobile and desktop certainly has piqued my interests.

 

 

 

Other other options…

 

This doesn’t even come close to listing all of the languages that compile to JavaScript, for a more complete list see this.  This does however cover the major players, at least as I see them.  If you think I made a major omission or mistake in this list, please let me know!

 

JavaScript is becoming more important and JavaScript programs are becoming more complex.  The language does have a number of flaws, but fortunately there are a number of options to help you cope, at least until ECMAScript 6 arrives.

General Programming


9. October 2012

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


GFS On YouTube

See More Tutorials on DevGa.me!

Month List