Windows 10 Progress widget with the HTML5 Canvas

I recently decided to take the plunged and updated from Windows 8 to Windows 10.  Wow! it seemed to take what felt like hours.  I was granted the privilege to see Microsoft’s new please wait progress tracker for quite sometime.  If you have not seen it; progress is measured through movement by using the perimeter of a circle.  As the progress moves from from zero, through to one-hundred percent the perimeter of the circle is filled, forming a simple and clean user interface.  This is the progress widget used during the upgrade:

Windows 10 Progress Widget

The mission of the posts is to explain how to replicate the above using HTML5’s canvas.

Continue reading “Windows 10 Progress widget with the HTML5 Canvas”

Advertisements

How to draw a Dartboard using HTML’s Canvas

This post will cover the steps required to draw a traditional Dartboard using HTML5’s canvas.  The final product produces the following rendered board.

Dartboard
Dartboard drawn using HTML5’s canvas

To tackle this task one’s thought process was to picture how one would draw a dartboard using layers.  In theory you would start by drawing the black circle that forms the base of the board.  Followed by the alternating black and while pie sections.  The double and treble arcs would then be placed accordingly, followed by the outer-bull and bulls-eye circles.  And finally, the wire-works between the pie sections and lettering on the outer ring.

Continue reading “How to draw a Dartboard using HTML’s Canvas”

Canvas Drag and Drop with Collision Detection

In this post I’ll cover the basics of implementing drag and drop with collision detection using the Canvas element and JavaScript. The end result will produce the following:

Drag and Drag shapes on the canvas

Each item on the canvas is represented by a rectangle.  When clicking inside the bounds of an rectangle the inner circle’s colour changes to grey to indicate the item is selected.  Release the button results in a mouse up event .  Between the mouse down and up events the item can be dragged and thus moved around the canvas.  When two objects collide they will be coloured red. This functionality has been implemented as follows. Continue reading “Canvas Drag and Drop with Collision Detection”

Automate screenshots with Node and Grunt

nodeThe official site claims ‘Node is built on Chrome’s JavaScript runtime it can be used for building fast, scalable network applications’.  Drilling into that verbiage; it is quite obvious what fast means.  Scalable is also semi-obvious; but, only within context.  Scalable in this context means an application – for example a website similar to twitter – can easily be modified to cater for increasing demand: such as the number of users accessing a site increasing.  Without understanding the technology behind sites such as twitter we can all imagine the amount of people tweeting at any one time – a lot.  How does the technology behind twitter handle this amount of activity: in short the answer is, by being scalable.  The final part of Node’s official statement refers to the ‘network application’.  This simply means the components that provide technology behind any given website and/or mobile app.   Continue reading “Automate screenshots with Node and Grunt”

Great Little Computer!

A simple HTML5 Game tutorial – Part 3

Following on from Part 2 we have put in place the foundation of our game and have some ‘bad guys’ moving in a menacing manner.  We are close to having a game: if we could just shot the ‘bad guys’.  Reminding ourselves of the goals set out in Part 1 we need to achieve the following: Continue reading “A simple HTML5 Game tutorial – Part 3”

Keyboard with historical game keys in orange

A simple HTML5 Game tutorial – Part 2

Following on from Part 1 we have put in place the foundation of our game.  But, we can’t really call it a game as we have no interaction. Reminder ourselves of the goal set out in Part 1 we need to achieve the following:

In you want to have a peek at the result of following this post click here.

Continue reading “A simple HTML5 Game tutorial – Part 2”

JavaScript the hoisting effect

JavaScript is one of the most talked about programming languages of the day. Being the language of the browser any modern programmer, developer or web designer cannot avoid it. It’s even sneaking onto our servers with courtesy of the node.js project. If you’re new to JavaScript there are a few ‘features’ that may trip you up, especially if you have been using a class based language. Take the following example in Java:

	public static void main(String[] args) {
		
		List<String> list = null;
		
		if((list = coloursInImage(img1)) != null) {
			
			int iNoOfColours = 0;
			
			iNoOfColours += list.size();
			System.out.println(iNoOfColours);
			
		}
		
		if((list = coloursInImage(img2)) != null) {
			
			int iNoOfColours = 0;
			
			iNoOfColours += list.size();
			System.out.println(iNoOfColours);
		}
	}

In Java the variable iNoOfColours will hold the size of the list as returned by the method ‘coloursInImage’. So if img1 has 8 colours and img2 two has 256 colours we’d see those numbers printed to the output window.

Let’s look at the JavaScript equivalent:

	var list = null,
		img1, img2;

	if((list = coloursInImage(img1)) !== null) {

		var iNoOfColours = Number();
		
		iNoOfColours += list.length;
		console.log(iNoOfColours);

	}

	if((list = coloursInImage(img2)) !== null) {

		var iNoOfColours;
		
		iNoOfColours +=	list.length;
		console.log(iNoOfColours);
	}

In JavaScript the variable iNoOfColours will hold the size of the array as returned by the method ‘coloursInImage’. So if img1 has 8 colours and img2 two has 256 colours we’d expect to see those numbers printed to the output window. However, we actually get 8 and 264. This is because of the hoisting effect – specifically how JavaScript works when handling declaration statements (var). Regardless of where a variable is declared, its declaration is hoisted to the top. The key here is to understand the declaration and initialization steps are treated separately and only the declaration will be hoisted. In our example, the first declaration also initialises the variable to 0. We then simply increment the variable’s value (zero) by the length of the array; thus, when repeating this within the second if-statement we end up summing the two. This is because the second declaration of the variable has been hoisted. The effect of which is that the expected scope does not mirror that we’d expect in Java. Something to watch out for!

JavaScript Design Pattern – Singleton Pattern

The singleton pattern is a design pattern which restricts the creation of an object to the same instance. In practical terms this means the variable defined below would be looking at the same object instance:

var object1 = new Car(),
object2 = new Car();

object2.colour = 'red';

The example above changes the colour property of object2. With the singleton pattern object1 is the same object, thus, the colour property of object1 also reflects the change. The pattern is useful when there is a need to coordinate the logic across decoupled and thus distinctly separate areas of code while maintaining access to a shared and consistent central object. Let’s look at an implementation of a singleton pattern:

function Game() {
    
    // the cached instance 
    var instance;
    
    // rewrite the constructor
    Game = function Game() {
        return instance;
    };

    // carry over the prototype 
    Game.prototype = this;

    // store the instance 
    instance = new Game();

    // reset constructor pointer 
    instance.constructor = Game;

    // default properties
    instance.lives = 3;
    instance.score = 0;

    return instance;
}

This code above creates an object called “Game”. To make sure the object is a singleton the constructor is rewritten during the object’s first invocation. This rewrite means any subsequent instances of the object simply returns the value of the instance variable. The instance variable within the object is set during the initial creation of the object prior to the new constructor being applied. Two properties are created after the line that rewrites the constructor; to repeat the above for clarity, this property creation will only be performed once for the first object.

Proving the above we can create two instances of the Game object and assert they are equal:


// update prototype and create instance
Game.prototype.player = "Greg";
var g = new Game();

// update prototype and create instance
Game.prototype.difficulty = 'hurt me plenty';

var g2 = new Game();

console.log("New player property works: " + (g.player === g2.player));
console.log("Both instances of Game are equal: " + (g === g2)); // true 
console.log("All prototype properties work: " + 
            (undefined !== 
                 (g.player && g.difficulty && g2.player && g2.difficulty)));
console.log("The initial score property works: " + g.score);
g2.score += 100;
console.log("The properties work after update: " + g.score);
console.log("The constructor points correctly: " + (g.constructor === Game));

The code above creates two instance of the Game object variables: ‘g’ and ‘g2’. The lines which follow then compare the two objects to assert the are truly equal. This will return the following result:

New player property works: true
Both instances of Game are equal: true
All prototype properties work: true
The initial score property works: 0
The properties work after update: 100
The constructor points correctly: true 

The implementation of the pattern is fairly simple. Although, the pattern does endure a fair amount of criticism. This is because the pattern implements a global space into your code which could be argued as being an anti-pattern. In my opinion used sparingly the pattern can be useful.

JavaScript Design Pattern – The Chaining Pattern

The basic theory of a chaining pattern is to call method after method of a given object without having to split the calls over several lines. Here is an example of calling several methods procedurally:

myObj.method1();

myObj.method2();

myObj.method3();
...
myObj.methodX();

And with a chaining pattern:

method1().method2().method3().methodX();

I can imagine you are asking, “What use is this? And how does it work?”. Well let us first look at a real world example. The JQuery library makes extensive use of this pattern. Take the following example for instant:

$('div').fadeOut(1800).
    fadeIn(1800).
    slideUp(800).
    slideDown(800).
    animate({height:'20px'}, 500).
    animate({width:'20px'}, 500).
    fadeOut(1800);

This implementation allows a user of JQuery to ‘chain’ together animations provided by JQuery. Very powerful! Other libraries such as ExtJS make similar use of the pattern.

To implement the chaining pattern each method must return the instance of the object being called. In other words they return the ‘this’ variable. In JavaScript ‘this’ always refers to the “owner” of the function we’re executing. Thus, this enables the next chained method to execute. A theoretical example of the above JQuery example follows:

var $ = function(selector) { 
    
    this.fadeOut = function(duration) {
        console.log('fadeOut');
        return this;
    }
    
    this.fadeIn = function(duration) {
        console.log('fadeIn');
        return this;
    }
    
    this.slideUp = function(duration) {
        console.log('slideUp');
        return this;
    }
    
    this.slideDown = function(duration) {
        console.log('slideDown');
        return this;
    }
    
    this.animate = function(style, duration) {
        console.log('animate');
        return this;
    }
    
    return this;
}

$('div').fadeOut(1800).
    fadeIn(1800).
    slideUp(800).
    slideDown(800).
    animate({height:'20px'}, 500).

This example simply prints the name of each invoked method to the console; however, it illustrates the pattern quite well.

With anything in life the pattern has advantages and disadvantages. The beauty of the pattern is that it makes the chained method read like a book: almost self documenting syntax! It is also concise and there is less to type for us busy developers. Another advantage of the pattern is that it forces us to split down our methods into smaller reusable chunks.

The disadvantages are it is harder to debug. If any of the methods within the chain fails you will only be informed that the line of code that failed is the one invoking the chain. Meaning the true error is hidden within the chained methods.

JavaScript: A private member variable design pattern

JavaScript does not include some of the common features of a class based language like Java or C++. Simple concepts such as private member variables are not available via in-built syntax. This can result in the global scope becoming littered with variables leading to name conflicts or variable corruption.
Continue reading “JavaScript: A private member variable design pattern”