Archive for February, 2013

Introducing CodePlus!

February 27, 2013 1 comment

CodePlus is an application that I wrote because I wanted a better coding experience on the Windows 8 RT devices since I could not run Visual Studio. Here is a description of CodePlus:

CodePlus – is an editor to allow developers to program in C, C++, C#, CoffeeScript, CSS, HTML, Java, JavaScript, Ruby, Perl, PowerShell, Python, VB.NET, and many more. It supports undo/redo and syntax highlighting. As a developer, you can point to a folder and work on any files in that file.

Here are a couple of screen shots of the application:









This application has kept me the busiest by far as I am getting requests for new languages to support and there are a lot of nuances around building a good editor. Luckily, there are some very good libraries available that help making this a breeze.

So what does the application do?

Well, it basically is a NotePad editor but with some added functionality and features.  I wanted to have built-in syntax highlighting for my code that I was working on.  I also wanted to have the ability to point to a folder and recursively display all the files available in the Explorer flyout.  This was important as I didn’t want to open each file for a project manually.  This is where I am trying to be more like Visual Studio with a project structure but only use folders as my driving factor.  I also wanted to be able to preview my HTML when I was coding it.  I wanted to allow for saving my files without interacting with a file picker after I had either loaded an existing file or created a new one.

Here is a list of the libraries that I am using:

CodeMirror – this is the library that does the bulk of the work for me.  (Note: Another similar library that you could use is Ace.)
jQuery – as you cannot point to a CDN for libraries, I wanted to provided jQuery support in my editor and preview tool.
KnockoutJS – I wanted not only to support this but I am also using it internally in the application as well.

I found that writing this application was not only challenging but also gratifying as I am very interested to see what other developers are looking for in an application and what they are looking for to make their development environment better.

When building Windows 8 applications using HTML5 and JavaScript, you are not allowed to point to any library on a CDN and download it at runtime. All libraries that you use must be part of the project. Not only that but most of these libraries are on GitHub or some other location and the file encoding does not match the requirements necessary for Windows 8. One last thing to note about third-party libraries is that you will probably fail the Windows 8 app certification process as the library will be considered unsafe. Luckily both the file encoding and, to some degree, un-safe code is easy to fix. For example, there are several versions of jQuery now that you can download that will pass Windows 8 app certification.

The only other “complaint” that I have with using third-party libraries is that I am stuck with manually updating my application when new versions of a library are available. I understand the security implications and why Microsoft has chosen to lock down and sandbox our applications but I wish this process could be easier.

From a support perspective, I am using UserVoice. Here is a link to my support site.  UserVoice is absolutely amazing and it gives your application the polish that it needs from a support perspective.  It provided a great way for me to get feedback for my application as well as posting FAQs and any support information I wanted.

Where do we go from here?

I would really like to add syntax checking to several of the languages that I support.  I get so much for free from CodeMirror that I don’t know how many languages I can support but it would be really nice to have this feature.

I would also like the ability to fully support the preview aspect of my HTML editor with regard to pulling in scripts or css from different file locations.  Due to the security nature of Windows 8, this isn’t easy but I believe that I can support relative scripts and links.

Again, writing this application has been a great learning experience and a joy.  I know I have said this in several blog posts but I truly love the ability to write native Windows 8 applications in HTML5, JavaScript and CSS3.

Hope this helps and gives you some ideas for your applications…

Introducing DoodlePad!

February 26, 2013 1 comment

Another simple but fun application that I wrote for my boys. DoodlePad is yet another paint-like clone that is touch enabled. I wanted to provide a simple means for my boys to play around and make me some cool drawings.

Here are a couple screens shots:

This is the splash screen.

Here is a screen showing my Appbar and NavBar.

Here is an example of the color picker I use.

Here is a simple example of my size picker I use as well.

Like my games, this application relies heavily on HTML5 canvas to get its job done. I also want to provide a link to a pure JavaScript color picker I used in the app in case any of you are looking for one.

I tried to find a control or some pure JavaScript that would allow me to do the size picker and I didn’t find one. I ended up building it myself as the process is really simple and can be used anywhere you need something to reflect size. First, I used an Input type of “range”. Next I positioned a DIV to the right of it.

Here is the HTML snippet of the flyout that I am using in my application:

<div class="flyout" id="sizeFlyout" data-win-control="WinJS.UI.Flyout"><label>Size: <input id="penSize" type="range" max="100" min="1" step="1" value="5" /></label>
<div id="actualSize"></div>

Next, I will show you the CSS I used:

#sizeFlyout {
    width: 425px;
#actualSize {
    background-color: black;

Finally, here is the JavaScript I used to adjust the size of the DIV and color:

var brushColor = "#df4b26";
var actualSize = document.getElementById("actualSize");
var penSize = document.getElementById("penSize");
penSize.addEventListener("change", function (element, e) { = penSize.value + "px"; = penSize.value + "px";
}, false);

As you can see, it is pretty simple and is a great technique to represent the size of an object based on a range or scale.

Another interesting feature that I struggled with a bit was allowing my boys to pick a background color or even open an existing image and use it as a background. My first approach was to simple paint this on to the canvas and it worked fine if the boys would pick a background color and start drawing but the moment they tried to pick a different background color it would overlay and cover up their drawing. I also noticed that the more I put into the canvas the more I had to worry about performance.

It turns out that my solution was simple, an HTML5 canvas is transparent by default and this turns out to be great. All I had to do was simply set the background color of the DIV that was wrapping my canvas.

This worked perfect until I tried to save my canvas out to a file. When I performed a save, I would get a transparent background because the “real” background was not part of the canvas. Here is the save function that I used. I am showing the full cycle from when the user clicks on the save button:

function saveAs() {
    // Verify that we are currently not snapped, or that we can unsnap to open the picker
    var currentState = Windows.UI.ViewManagement.ApplicationView.value;
    if (currentState === Windows.UI.ViewManagement.ApplicationViewState.snapped &&
        !Windows.UI.ViewManagement.ApplicationView.tryUnsnap()) {
        // Fail silently if we can't unsnap

    var encoderId;
    var filename;
    var stream;

    var imgData;

    // Create the picker object and set options
    var picker = getFilePicker("save");

    picker.pickSaveFileAsync().then(function (file) {
        if (file == null) return;
        filename =;

        if (file) {
            switch (file.fileType) {
                case ".jpg":
                    encoderId = Windows.Graphics.Imaging.BitmapEncoder.jpegEncoderId;
                case ".bmp":
                    encoderId = Windows.Graphics.Imaging.BitmapEncoder.bmpEncoderId;
                case ".png":
                    encoderId = Windows.Graphics.Imaging.BitmapEncoder.pngEncoderId;
            return file.openAsync(Windows.Storage.FileAccessMode.readWrite);
        } else {
            return WinJS.Promise.wrapError("No file selected");
    }).then(function (_stream) {
        stream = _stream;

        // BitmapEncoder expects an empty output stream; the user may have selected a
        // pre-existing file.
        stream.size = 0;

        return Windows.Graphics.Imaging.BitmapEncoder.createAsync(encoderId, stream);
        //return Windows.Graphics.Imaging.BitmapEncoder.createAsync(Windows.Graphics.Imaging.BitmapEncoder.pngEncoderId, stream);
    }).then(function (encoder) {
        var canvas = id("doodleCanvas");
        var width = canvas.width;
        var height = canvas.height;
        var ctx = canvas.getContext("2d");

        var canvas2 = id("canvas2");
        canvas2.width = width;
        canvas2.height = height;
        WinJS.Utilities.removeClass(canvas2, "hidden");
        var ctx2 = canvas2.getContext("2d");
        var root = document.getElementById("root");
        if ( !== "") {
            ctx2.drawImage(currentImage, 0, 0, width, height);
        else if ( !== "") {
            ctx2.fillStyle =;
            ctx2.fillRect(0, 0, width, height);
        ctx2.drawImage(canvas, 0, 0);

        imgData = ctx2.getImageData(0, 0, width, height);
        WinJS.Utilities.addClass(canvas2, "hidden");

            96, // Horizontal DPI
            96, // Vertical DPI

        //Go do the encoding
        return encoder.flushAsync();
    }).then(function () {
        WinJS.log && WinJS.log("Saved new file: " + filename, "sample", "status");
        //id("buttonSave").disabled = false;
        //id("buttonRender").disabled = false;
    }).then(null, function (error) {
        WinJS.log && WinJS.log("Failed to save file: " + error.message, "sample", "error");
    }).done(function () {
        stream && stream.close();

If you haven’t played with Promises, I would suggest you do as they make asynchronous programming a lot easier in JavaScript. My function saveAs gets called whenever the save button is pressed. I then proceed to display a Save File Picker. Once the user has picked a file name or existing file, I grab the stream object and pass it to my encoding. It is here that I perform a simple swap operation where I use two canvas objects. This allows me to “paint” the background on the original canvas while still saving its content on a dummy canvas. I then just dump the contents from the dummy back onto the original canvas.

All in all, I have plans to continue to improve the application. The boys have requested the ability to have stamps or stencils. They would like to have simple shapes to draw as well as the ability to have stock images for them to color. They also wanted to have a crayon effect and some others that they have used in the past.

Hope this helps….

Introducing Tank Commander!

February 26, 2013 1 comment

In this post, I wanted to describe Tank Commander and talk about some of the logic that went into building it.

Here is the description of the game:

Tank Commander is a game that teaches you programming logic. You get one chance to write your program and destroy the base. You can play any level but your real skill comes when you can write all the programs without a single error!

The following are some of the screens in the game:

Tank Commander - Splash

Main Screen






The main premise behind the game was to use it as a tool for teaching my boys how to think logically and perform some simple programming. My oldest can win each level with a couple of tries. My youngest is still working but he has the first couple levels down perfect!

I have really enjoyed building games using HTML5 and the Canvas. It is so easy with CreateJS and the suite of tools it provides. I have looked at other libraries but it keeps pulling me back to use it for my games so far. I decided to build on the simple level editor that I built for my first game, Milo the Mosquito as it was a very straight forward approach. I did, however, make it a little more complicated as I wanted to have a little more metadata about the levels.

Probably, one of the most challenging parts about creating the game, was trying to make sure that I had a good collision detection.  I didn’t really need to worry about this in my other game but now with moving objects, I needed to be a little more careful.  Thankfully, due to the grid that I was using, I simply rolled out a poor man’s collision detection system using the X and Y coordinates.  That is one of the reasons why you see them in the game. There were originally meant for debugging purposes only but I liked them so much that I decided to keep them.

I also had to create a simple parser for the input the user typed into the programming console. I know that this experience can be improved upon by providing some compiler errors or hints to help the user play the game.

In my first release I provided a toggle for all sounds in the game but I changed that a little in the next release to have a toggle for both sounds and music in the game. I also decided to save the settings of what the user chose automatically so that when they came back to the game it would be ready.

Another area that I found was not the most intuitive was the original main menu. When a user went to the selected a level from the dropdown, the level automatically started. This was very irritating if you clicked on the home button in a level and then wanted to go back.

I now have a “Go” button that takes the user to the selected level.

In my original design of Milo the Mosquito, I had a separate level text file. I changed this up a little and now use JSON for Tank Commander. This provided me with the ability to define more complex levels and behaviors.

The following is the first level for Tank Commander as JSON:

	"id": 1,
	"name": "Fire!",
	"level": "intro",
	"background": [
	"game": [
	"tankDirection": "north"

I left out the rest of the levels for brevity. I have two layers to my game so that I could create a background and then position the other assets on the screen. I finally have a direction so that I can tween the tank into the correct orientation. This is also beneficial as it allow me to have a single sprite sheet with animation going in a single direction and be able to tween all the other direction by just rotating the items.

Here is a quick legend of what I am doing with the “background” and “game” arrays.  I wanted to have a background where I could define a nice border instead of the same tile.  This is the reason for the following values: 1, N, 2, W, E, 3, S, 4.  It doesn’t take a lot of imagination to see what I am representing here.  I also used the “.” character to represent the tiles within the border.

The “game” array is basically the same, I am representing different tiles by using different characters: P, T, X.

Here is a screen shot of the layer rendered:


This is a simple approach and can be used for a lot of time layouts.  It is used in a lot of 2D platform games.

Although, I have ran into some challenges while developing this game, I really enjoyed building it using HTML5 Canvas and JavaScript.  The other thing that I absolutely love is the ability now to natively target Windows 8.

Hope this helps and inspires you to write one as well…

Developing Windows 8 – Hex Math

February 20, 2013 1 comment

I recently was working on an application where I wanted to use a simple color picker and then make the button that I used to launch the color picker display the color chosen. The library that I ended up using can be found here. I selected it because I didn’t want any dependencies on jQuery or other libraries and just use a lightweight JavaScript approach.


As you can see, I am using the built-in AppBar/NavBar features of Windows 8 to help keep the UI clean.

One problem I ran into while testing my code was that when I picked either a background or brush color that was white, I could no longer see the icon and text on my command bar.

This is what my markup looks like for the color selectors:

<div id="navBar" data-win-control="WinJS.UI.AppBar" data-win-options="{placement: 'bottom'}"><button data-win-control="WinJS.UI.AppBarCommand" data-win-options="{id:'bgColor', label:'Background', icon:'fontcolor', section:'selection', type:'flyout', flyout: select('#backgroundColorFlyout')}"></button>
 <button data-win-control="WinJS.UI.AppBarCommand" data-win-options="{id:'color', label:'Brush Color', icon:'fontcolor', section:'selection', type:'flyout', flyout: select('#colorFlyout')}"></button></div>
<div class="flyout" id="colorFlyout" data-win-control="WinJS.UI.Flyout"></div>
<div class="flyout" id="backgroundColorFlyout" data-win-control="WinJS.UI.Flyout"></div>

The following is the solution I used:

var BLACK = "#000000";
var WHITE = "#ffffff";
var WHITE_THRESHOLD = 13289158;

function bgColorInit(elementName, hex) {
    var bgColor = document.getElementById(elementName);
    var bgLabel = bgColor.getElementsByClassName("win-label")[0];
    var bgImage = bgColor.getElementsByClassName("win-commandimage")[0];
    var bgRing = bgColor.getElementsByClassName("win-commandring")[0]; = hex;
    var h2d = parseInt(hex.substring(1), 16);
    if (h2d > WHITE_THRESHOLD) { = BLACK; = BLACK; = BLACK; = BLACK;
    else { = WHITE; = WHITE = WHITE = WHITE;

The one thing that I did learn was that Windows 8 uses a lot of CSS classes to perform its look and feel. I did a little research and found the classes that I need and grabbed the underlying objects that there were attached to. Next, I simply updated the color and border color of the elements to the corresponding WHITE or BLACK colors.

You have to be careful as I had to parse the Hex value I had first. As you can see, the Hex string also contains the “#” symbol. Next, I simply used the parseInt function specifying 16 for the radix number.

I did a little playing around and found the following 13289158 to be a good number as a threshold for white colors. I didn’t want to only update the screen when it was completely white as I lost visibility of the text and icons for even lighter shades of white.

Again, this was just a simple approach to a bigger problem. I wanted to have a simple color selector and thought that by using the button itself as the color indicator, I could keep my user interface clean.

Here is what the screen looks like now with my fix:

Color Picker - White background with Black text

Here is a screenshot of the Color Picker in action using a Flyout as well:

Color Picker

Hope this helps…

Developing Windows 8 – Saving your canvas

February 20, 2013 1 comment

Developing applications for Windows 8 has been so much fun now that we can use HTML5, CSS3, and JavaScript.  I have been inspired to write some simple applications for the Windows 8 App Store.  This has been a very fun experience and I find that the more that I try and push myself, the more I end up learning.

I recently just released a new application for drawing called, “DoodlePad“.  This simple application allows you to draw on the canvas and change your brush color, size, and background of your canvas.  It also allows you to save your drawing, create a new one, or open an existing image.  One of the tricky parts that I ran into when developing this application was trying to provide a good user experience by allowing them to have a background color.

This wasn’t as easy as I had first imagined since the Canvas is transparent by default.  At first I thought I could simply create a fill style and then fill the Canvas rectangle with whatever color a user chose.  However this didn’t work out very well when I was testing because as soon as I would start drawing and then want to change the background, all of my art work up till then would be covered with the new background.

Here is what I came up with, I decided to use a wrapping DIV that I would set the “background-color” property using JavaScript whenever the user selected a different color.  This turned out to work perfectly well due to the Canvas being transparent out of the box.

Now comes the problem, when I want to dump all the beautiful work that the user has done create a masterpiece, the canvas no longer has any information concerning the background.

The following code snippet will demonstrate what I had to do to get this working so that I could allow my users to save their artwork including the backgrounds:

var canvas = id("doodleCanvas");
var width = canvas.width;
var height = canvas.height;
var ctx = canvas.getContext("2d");

var canvas2 = id("canvas2");
canvas2.width = width;
canvas2.height = height;
WinJS.Utilities.removeClass(canvas2, "hidden");
var ctx2 = canvas2.getContext("2d");
var wrapper = document.getElementById("canvasWrapper");
if ( !== "") {
    ctx2.fillStyle =;
    ctx2.fillRect(0, 0, width, height);
ctx2.drawImage(canvas, 0, 0);

imgData = ctx2.getImageData(0, 0, width, height);
WinJS.Utilities.addClass(canvas2, "hidden");

The following is what the HTML looks like:

<div id="canvasWrapper">
    <canvas id="canvas2"></canvas>
    <canvas id="doodleCanvas"></canvas>

In a nutshell, I am simply applying the background color from the wrapper DIV and setting it as the fill color for the context of the “canvas2” canvas object. Then, I simply draw what was on the content of the first canvas onto the “canvas2” object. You will also notice that I am adding and removing a class that simply hides “canvas2”.

Here is the CSS for the “hidden” class:

.hidden {
    visibility: hidden;

A final note
One thing that took longer than I originally anticipated, was that when I first tried this approach, I was getting really inconsistent behavior on the screen from the user’s perspective. I would lose touch capabilities and also lose the drawing altogether. The solution I found is very simple and I was surprised that not having these CSS properties set caused so many problems:

canvas {

I found that it was necessary to ensure that both of the canvas objects were exactly the same size and positioned in the same place.

Hope this helps…

Categories: English Tags: , , , ,