August 13, 2012

Introduction to data structures and algorithms in javascript: Doubly Linked Lists

This is a continuation of a series introducing data structures in javascript. A linked list is a
data structure consisting of a group of nodes that represent a sequence. Each element in a linked
list has a data field and a field that points to the the next node in the linked list. A doubly
linked list also includes a field that points to the previous node in the linked list.

The first step in creating a doubly linked list in javascript is to define a custom type. A doubly
linked list should be defined with a length property, a ‘head’ property which points to the first
element in the list, and a ‘tail’ property which points to the last element in the list.

function DoublyLinkedList() {
	this.length = 0;
	this.head = null;
	this.tail = null;
}

Adding an item to the list is simply a matter of updating the ‘tail’ property with the new item and
updating the previous ‘tail’ item to have a ‘next’ value of the new node. If the length of the list
is zero, the ‘head’ and ‘tail’ properties are set to the node that is being added; making it the
first item in the list.

DoublyLinkedList.prototype = {
	add: function(value) {
		var node = {
			value: value,
			next: null,
			previous: null,
		}
		
		if (this.length == 0) {
			this.head = node;
			this.tail = node;
		}
		else {
			this.tail.next = node;
			node.previous = this.tail;
			this.tail = node;
		}
		
		this.length++;
	},
};

To retrieve a value from the list, it requires that you traverse the list to find the node for a
given index. If an index is provided that does not exist in the list, then a null value should be
returned.

DoublyLinkedList.prototype = {
	getNode: function(index) {
		if ( index > this.Length - 1 || index < 0 ) {
			return null;
		}
		
		var node = this.head;
		var i = 0;
		
		while (i++ < index) {
			node = node.next;
		}
		
		return node;
	},
	
	displayNode: function(index) {
		var node = this.getNode(index);
		if (node != null) {
			document.writeln('value = ' + node.value + '<br />');
			document.writeln('previous = ' + (node.previous != null ? node.previous.value : 'null') + '<br />');
			document.writeln('next = ' + (node.next != null ? node.next.value : 'null') + '<br />' );
			return;
		}
		
		alert('invalid index!');
	},
};

Note that displayNode is just a convenience function for the purpose of this demonstration. In any
case, you should check that the previous or next node is not null before attempting to access the
value.

The final core operation of implementing a doubly linked list is providing the ability to remove an
element. Removing an element from the list is a bit tricky because the previous node and next node
will need to have their properties updated. Any remove operation should handle the case where the
element to be removed is the first or last one. In both of these cases, you will need to update the
‘tail’ and ‘head’ property appropriately. Removing all other elements involves a similar lookup that
is done in the getNode() function. The length should also be manually updated.

DoublyLinkedList.prototype = {
	remove: function(index) {
		if ( index > this.Length - 1 || index < 0 ) {
			return null;
		}
		
		var node = this.head;
		var i = 0;
		
		if (index == 0) {
			this.head = node.next;
			
			// check if we removed the only one in the list
			if (this.head == null) {
				this.tail = null;
			}
			else {
				this.head.previous = null;
			}
		}
		else if (index == this.length - 1) {
			node = this.tail;
			this.tail = node.previous;
			this.tail.next = null;
		}
		else {
			while (i++ < index) {
				node = node.next;
			}
			
			node.previous.next = node.next;
			node.next.previous = node.previous;
		}
		
		this.length--;
	},
};

For convenience, the following is the complete implementation with sample usage.

function DoublyLinkedList() {
	this.length = 0;
	this.head = null;
	this.tail = null;
}

DoublyLinkedList.prototype = {
	add: function(value) {
		var node = {
			value: value,
			next: null,
			previous: null,
		}
		
		if (this.length == 0) {
			this.head = node;
			this.tail = node;
		}
		else {
			this.tail.next = node;
			node.previous = this.tail;
			this.tail = node;
		}
		
		this.length++;
	},
	
	getNode: function(index) {
		if ( index > this.Length - 1 || index < 0 ) {
			return null;
		}
		
		var node = this.head;
		var i = 0;
		
		while (i++ < index) {
			node = node.next;
		}
		
		return node;
	},
	
	displayNode: function(index) {
		var node = this.getNode(index);
		if (node != null) {
			document.writeln('value = ' + node.value + '<br />');
			document.writeln('previous = ' + (node.previous != null ? node.previous.value : 'null') + '<br />');
			document.writeln('next = ' + (node.next != null ? node.next.value : 'null') + '<br />' );
			return;
		}
		
		alert('invalid index!');
	},
	
	remove: function(index) {
		if ( index > this.Length - 1 || index < 0 ) {
			return null;
		}
		
		var node = this.head;
		var i = 0;
		
		if (index == 0) {
			this.head = node.next;
			
			// check if we removed the only one in the list
			if (this.head == null) {
				this.tail = null;
			}
			else {
				this.head.previous = null;
			}
		}
		else if (index == this.length - 1) {
			node = this.tail;
			this.tail = node.previous;
			this.tail.next = null;
		}
		else {
			while (i++ < index) {
				node = node.next;
			}
			
			node.previous.next = node.next;
			node.next.previous = node.previous;
		}
		
		this.length--;
	},
};

var list = new DoublyLinkedList();
list.add("zero");
list.add("one");
list.add("two");
list.add("three");

list.displayNode(2); // prints value = two, previous = one, next = 3
list.remove(2);
list.displayNode(2); // prints value = three, previous = one, next = null
Advertisement
Tags:
August 12, 2012

Introduction to data structures and algorithms in javascript: Stacks and Queues

This is a continuation of a series introducing data structures in javascript. In the last couple of
posts, the javascript Array was introduced and it is recommended to have an understanding of the
javascript Array before reading this article.

Stack

A stack is a linear data structure and abstract data type in which operations are performed via the
last in, first out (LIFO) methodology. Similar to other programming languages there are two main
methods in javascript used to populate and retrieve data in the stack. These methods are ‘push’
and ‘pop’. The ‘push’ method is used to add an element to the top of stack and the ‘pop’ method is
used to remove the top element from the stack.

In javascript, the Array object is used for a stack implementation. Javascript has a push() and a
pop() method for the Array object which makes the implementation rather simple.

	var stack = new Array();
	stack.push("one");
	stack.push("two");
	stack.push("three");

	document.writeln(stack.pop() + " - stack length:" + stack.length); // prints "three - stack length: 2"
	document.writeln(stack.pop() + " - stack length:" + stack.length); // prints "two - stack length: 1" 
	document.writeln(stack.pop() + " - stack length:" + stack.length); // prints "one - stack length: 0" 

One key point to understand is that when pushing an element to the stack it is adding it to the end
of the Array. This may be counter intuitive since it is commonly referred to as the “top of the stack”.

Another point to understand is that when you use the pop method it removes the last element from the
Array as indicated in the code sample when it prints the Array length.

Queue

A queue is also a linear data structure and abstract data type with one key difference from a stack
being that it uses a first in, first out (FIFO) methodology. Another name for a queue is a buffer.
Typical usage of a queue would be for instances where you have more data to manipulate than you can
handle in a single period of time.

In javascript, the Array object is also used for a queue implementation. The unshift() method is
used to add elements to the beginning of an Array; ensuring that when you use pop() you get the first
element that was added to the Array.

	var queue = [];
	queue.unshift("one");
	queue.unshift("two");
	queue.unshift("three");

	document.writeln(queue.pop() + " - queue length:" + queue.length); // prints "one - queue length: 2"
	document.writeln(queue.pop() + " - queue length:" + queue.length); // prints "two - queue length: 1" 
	document.writeln(queue.pop() + " - queue length:" + queue.length); // prints "three - queue length: 0" 
Tags:
August 6, 2012

Introduction to data structures and algorithms in javascript: Arrays pt. 2

This is a continuation of a series on data structures in javascript. If you have been following
along, the last post introduced the javascript Array. This week we will take a closer look at some of the
methods available in javascript to manipulate an Array.

Array.concat

Array.concat joins two or more Arrays to create a new Array. Since it creates a new Array, it’s
important to understand that the original Array’s will remain unchanged.

var someArray = [ 1, 2, 3 ];
var anotherArray = [ 4, 5, 6 ];

var combinedArray = someArray.concat(anotherArray);
document.writeln(combinedArray); // prints 1, 2, 3, 4, 5, 6

Array.every

Array.every is a method that accepts a function as an argument. Each element in the Array is passed
to the function and evaluates if a condition is true or false. If all elements return true for the
Array, then the every method will return true. If at least one element returns false, then the
every method will return false.

var someArray = [ 1, 2, 3 ];
var anotherArray = [ 4, 5, 6 ];
var evaluateNum = 6;

var isLessThan = function(value) {
	return value < evaluateNum;
}

document.writeln(someArray.every(isLessThan)); // prints 'true'
document.writeln(anotherArray.every(isLessThan)); // prints 'false'

Array.filter

Array.filter will create a new Array of elements that evaluate to true in the given function. This
method passes the current value, the index, and a pointer to the array to the function.

var someArray = [ 1, 2, 3, 4, 5, 6 ];
var evaluateNum = 4;

var isLessThan = function(value) {
	return value < evaluateNum;
}

document.writeln(someArray.filter(isLessThan)); // prints 1, 2, 3

Array.forEach

Array.forEach passes each element of the Array to a given function. This is all this method does.
There is no return value. It’s simply an alternate to the common for loop and may be useful for
reusing common logic while looping through Array’s.

var someArray = [ 1, 2, 3 ];

var printArray = function(value, index) {
	document.writeln(index +' - '+ value);
}

someArray.forEach(printArray); // prints 0 - 1, 1 - 2, 2 - 3

Array.join

Array.join will output an Array as a string with a given delimiter. It is useful for sending a
string to the server that can be parsed using the delimiter.

var someArray = [ 1, 2, 3 ];
var delimited = someArray.join('-');

document.writeln(delimited); // prints 1-2-3

Array.indexOf

Array.indexOf will search the Array until it finds a match for a give search criteria. Once the
match is found, it will return the index of the matching element. It is important to note that it
will return the first match only. It will return -1 if no matches are found.

var someArray = [ 1, 2, 3, 3, 4, 5 ];

document.writeln(someArray.indexOf(3)); // prints 2
document.writeln(someArray.indexOf(9)); // prints -1

Array.lastIndexOf

Array.lastIndexOf provides the same functionality as Array.indexOf, but searches for a match in
reverse order.

var someArray = [ 1, 2, 3, 3, 4, 5 ];

document.writeln(someArray.lastIndexOf(3)); // prints 3
document.writeln(someArray.lastIndexOf(9)); // prints -1

Array.map

Array.map will return a new array containing values in the Array that are determined by a given
function.

var someArray = [ 1, 2, 3, 4, 5, 6 ];
var evaluateNum = 4;

var isLessThan = function(value) {
	if  (value < evaluateNum) {
		return 1;
	}
	return 0;
}

var newArray = someArray.map(isLessThan);
document.writeln(newArray); // prints 1, 1, 1, 0, 0, 0

Array.reverse

Array.reverse intuitively reverses the order of the Array.

var someArray = [ 1, 2, 3, 4, 5, 6 ];
someArray.reverse();

document.writeln(someArray); // prints 6, 5, 4, 3, 2, 1

These are the most commonly used useful Array methods. In the next post, we will introduce some of
the more advanced methods including methods used for creating stacks and queues.

Tags:
July 31, 2012

Introduction to data structures and algorithms in javascript: Arrays

This is a continuation of a series on data structures in javascript. This week’s topic is the Array. An Array is an enumerated list of variables; meaning that each value can be referenced by a numerical index. The index number is referenced using square bracket syntax and Arrays in javascript are zero based.

document.writeln(someArray[0]);

Numerical based indexes make it easy to loop through an Array.

for (i=0; i < 10; i++) {
    document.writeln(someArray[i] + '<br>');
}

There are two different ways to create an Array in javascript. The first way is to use the new operator, but current best practices dictate that the new operator should not be used on javascript primitives.

var someArray = new Array(10);

However, since the new operator has a chance (very slim) to produce unexpected results, standard practice for creating an Array is to simply use square brackets.

var someArray = [];

If you have some experience with Arrays in other programming languages like C or C++, you may be wondering how to define the size of the Array. In javascript it is not necessary because the size will be automatically increased as needed.

Javascript Arrays can be initialized with data or you can create an empty Array and add data at a later time.

var someArray = [ 1, 2, 3 ];

var anotherArray = [];
anotherArray[0] = 1;
anotherArray[1] = 2;
anotherArray[2] = 3; 

You can skip indexes when populating the array and the value of the skipped indexes will be ‘undefined’

var someArray = [];
someArray[0] = 1;
someArray[1] = 2;
someArray[3] = 3;
document.writeln(someArray[2]);     // prints 'undefined' 

Arrays in other languages can be rigid about the type of data that is stored. Typically all of the data stored in the Array would need to be of the same type. This is not the case in javascript where you can store any type of data in the same Array. This means that you can add strings, functions, objects, booleans, or even additional Array’s to a single Array.

var someArray = [];
var someArray[0] = 1;
var someArray[1] = 'yojimbo';
var someArray[2] = {'firstName': 'John', 'lastName':'Doe'};
document.writeln(someArray[2].firstName); // prints 'John' 

An important characteristic of javascript Arrays to understand is that they are passed by reference to functions. This means that anything that you do inside of the function will alter the original Array.

var someArray = [0, 1,2];

function updateArray(passedArray) {
    passedArray[0] = 3;
} 

updateArray(someArray);
document.writeln(someArray[0]);    // prints '3'

Similarly, javascript Arrays are assigned by reference. This means that if you create an Array by assigning it to an existing Array, anything that you do with the second variable will alter the original Array.

var someArray = [0,1,2];
var anotherArray = someArray;

anotherArray[0] = 3;
document.writeln(someArray[0]);    // prints '3'
Tags:
July 24, 2012

Introduction to data structures and algorithms in javascript: Associative Arrays

This is the first of a series of posts that will provide a beginner level introduction to data structures and algorithms in javascript.

A fundamental data structure in javascript is the Associative Array. An Associative Array is an abstract data type that is composed of a collection of key, value pairs such that each key exist only once in the collection.

The reason that an Associative Array is considered to be a fundamental data structure in javascript is that every object in the language is in fact an Associative Array.

Consider the following example:

var someArray = new Object();
someArray["A"] = 0;
someArray["B"] = 1;
someArray["C"] = 2;

You can get the values stored in the array by referencing the indexes or by object qualified naming:

alert(someArray["C"]);  // value by index
alert(someArray.C); // value by object qualified naming

An Associative Array can also be created using object literal notation:

var someArray = {A:0,  B:1, C:2};

Doing so creates the exact same array as the earlier example.

An important characteristic of the Associative Array in javascript is the fact that it is an object. In other languages, creation of an array requires that you explicitly define the data type. Any addition to the array that is of a different data type would result in an error. In javascript, the array object is defined by its members.

For example, you can add a method to an associative array:

var someArray = {A:0,  B:1, C:2}
someArray.Count = function() {
    return 3;
}

This is an important concept for beginners to understand because it may lead to some unexpected behavior. For example, looping through the array will show that there are four elements rather than three.

for(ind in someArray) {
    alert(ind);
}

This problem is typically solved in javascript by creating your own collection object.

var Collection = function() {
    this.count = 0;
    this.collection = {};
}

This defines a property for the count and an empty array. To make the collection object useful, it needs methods for adding and deleting elements from the collection array. These methods will update the count property.

this.add = function(key, item) {
    this.collection[key] = item;
    this.count  +=  1;
}
this.remove = function(key, item) {
    this.collection[key] = item;
    this.count  -=  1;
}

The collection object can now be used in the following manner:

var someCollection = new Collection();
someCollection.add("A", 0);
someCollection.add("B", 1);
someCollection.add("C", 2);
alert(someCollection.count);
alert(someCollection.collection["A"];
someCollection.remove("C");
Tags:
July 9, 2012

List recent WordPress Blog Posts with javascript

Last week we discussed listing recent blog posts in ASP.NET MVC using the SyndicationFeed class. One thing that I do not like about that solution is that it is server side, so this week we will look at getting the same functionality client side using javascript.

After searching a bit for existing solutions, I found that the Google Feed API is ideal for the task. It’s extremely simple to implement and provides the expected functionality.

The first step is to add the api to your page.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"> </script>

Note that jQuery is not required for the api, but it will be used later in this document.

Next, load the Feed API with the google.load method.

<script type="text/javascript">
	google.load("feeds", "1")
</script>

Once the ‘feeds’ module is set up to be loaded, create a div that will act as a container for the blog post list.

<div id="feedContainer" ></div>

Lastly, with some simple javascript we can dynamically build a list of the feed items.

<script type="text/javascript">
	var feedUrl = "https://blog.yojimbocorp.com/feed/";
	var feedContainer=document.getElementById("feedContainer");
	
	$(document).ready(function() {
		var feed = new google.feeds.Feed(feedUrl);
		feed.setNumEntries(10);
		feed.load( function(result) {
			list = "<ul>";
			if (!result.error){
				var posts=result.feed.entries;
				for (var i = 0; i < posts.length; i++) { 
					list+="<li><a href='" + posts[i].link + "'target=_blank'" + "'>" + posts[i].title + "</a></li>";
				}
				list+="</ul>";
				feedContainer.innerHTML = list;
			}
			else {
				feedContainer.innerHTML = "Unable to fetch feed from " + feedUrl;
			}					
		});
	});
</script>

Once complete, your page should look similar to the following.

<!DOCTYPE HTML>
<html>
	<head>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
	<script type="text/javascript" src="http://www.google.com/jsapi"> </script>
	<script type="text/javascript">
		google.load("feeds", "1")
	</script>
	</head>
	<body>
		<div id="feedContainer" ></div>
		<script type="text/javascript">
			var feedUrl = "https://blog.yojimbocorp.com/feed/";
			var feedContainer=document.getElementById("feedContainer");

			$(document).ready(function() {
				var feed = new google.feeds.Feed(feedUrl);
				feed.setNumEntries(10);
				feed.load( function(result) {
					list = "<ul>";
					if (!result.error){
						var posts=result.feed.entries;
						for (var i = 0; i < posts.length; i++) {
							list+="<li><a href='" + posts[i].link + "'target=_blank'" + "'>" + posts[i].title + "</a></li>";
						}
						list+="</ul>";
						feedContainer.innerHTML = list;
					}
					else {
						feedContainer.innerHTML = "Unable to fetch feed from " + feedUrl;
					}
				});
			});
		</script>
	</body>
</html>

If your page requires additional information about each post (description, author, categories, etc), be sure to look into using feed.setResultFormat and google.feeds.Feed.JSON_FORMAT.

July 2, 2012

List recent WordPress Blog Posts in ASP.NET MVC

Recently I was tasked with adding a list of recent blog posts from our WordPress site inside of an ASP.NET MVC web site. The initial strategy was going to involve fetching from the RSS feed, but after discovering the WordPress supported XML-RPC, I decided to explore that route first.

Using XML-RPC was supposed to be easy considering there is an available .NET library for it created by Charles Cook. The task should have been further simplified because there are several C# WordPress wrappers available.

After spending time with a couple of the WordPress wrappers available, it quickly became clear that the process of updating the wrappers to comply with the latest version of WordPress would be far more work than it was worth; especially considering the scope of this task.

So it was back to the original strategy of creating an RSS reader specifically for WordPress. After digging around a bit, I thankfully stumbled across the Syndication Feed class that is available in .Net 4.0 and above.

The Syndication Feed class basically provides the quick and easy solution that I was looking for while exploring the XML-RPC route. It really turned out to be a lot easier than I thought it could ever be.

So let’s get started. For this, I will assume that you are using an existing MVC application.

The first step is to add a reference to System.ServiceModel to your project as this is where the Syndication Feed class resides.

The second step is to create a View Model that will define a List of SyndicationItem’s:

using System.Collections.Generic;
using System.ServiceModel.Syndication;

namespace MvcApplication1.Models
{
    public class FeedViewModel
    {
        public FeedViewModel()
        {
            Posts = new List<SyndicationItem>();
        }

        public List<SyndicationItem> Posts { get; set; } 
    }
}

And in the Controller, we will need to populate the list:

using System.Linq;
using System.Web.Mvc;
using System.ServiceModel.Syndication;
using System.Xml;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new FeedViewModel();

            using (var reader = XmlReader.Create("https://blog.yojimbocorp.com/feed/"))
            {
                var feed = SyndicationFeed.Load(reader);
                foreach (var post in feed.Items.Take(10))
                {
                    model.Posts.Add(post);
                }
            }

            return View(model);
        }
    }
}

You will of course want to customize the reader URL to be your own and most likely will want to create a configuration entry for it.

And finally, display the data in your view:

@model MvcApplication1.Models.FeedViewModel
           
@foreach (var post in Model.Posts)
{
    <td><a href="@post.Id" target="_blank">@Html.DisplayFor(model => post.Title.Text)</a></td>
    <br />
    
}

I highly recommend reviewing the SyndicationItem documentation when creating your view.

June 18, 2012

A simple drawing grid with HTML5 part 4

This week, we will complete the simple drawing grid by adding support for mobile browsers. Support for mobile browsers consists of enabling interaction with the canvas with touch events rather than the mouse events that are currently used.
The first step however is to add some detection for whether or not the client is using a mobile device. There really isn’t a standard way to accomplish this that I am aware of, but we can use a bit of javascript to do the job.

var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i) ? true : false;
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i) ? true : false;
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i) ? true : false;
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i) ? true : false;
    },
    Any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Windows());
    }
};

This is not a comprehensive detection of all mobile devices, but should cover the most popular ones.

Once we determine if the client is using a mobile browser, we can choose wheter or not to bind mouse events or touch events. This is a simple matter of adding an if condition when the page has been loaded.

if (!isMobile.Any()) {
	alert('not mobile');
	$("#grid").mousedown(function(e) {
		mouseDown = true;
	}).bind('mouseup', function() {
		mouseDown = false;
	}).bind('mouseleave', function() {
		mouseDown = false;
	});
	
	$("#grid").mousemove(function(e) {
		if (mouseDown) {
			drawOnCanvas(e);
		}
	});
} else {
	grid_canvas.addEventListener('touchstart', function(e) {
		mouseDown = true;
	});
	
	grid_canvas.addEventListener('touchend', function(e) {
		mouseDown = false;
	});
	
	grid_canvas.addEventListener('touchmove', function(e) {
		e.preventDefault();
		if (mouseDown) {
			drawOnCanvas(e);
		}
	});
}

You should note that by default, some mobile browsers have the default behavior for ‘ touchmove’ already defined to move the entire browser window. We can disable this by adding the following to the ‘touchmove’ event that is bound to the canvas.

e.preventDefault();

Now that we have detection and handling for mobile browsers, the drawing grid is supported in both mobile and non-mobile web browsers. As an exercise, you may choose to increase the size of the canvas and controls to make it more visible for mobile devices with smaller screens.

The entire source for our completed drawing grid application can be seen by viewing the source of the demo.

June 14, 2012

A simple drawing grid with HTML5 part 3

This is a continuation of our simple drawing grid series. Last week, we ended up with a functional drawing grid with a few expected controls like setting pen size and pen color. While it was functional, it left a lot to be desired from a presentation standpoint. This week, we will work on giving our application a little bit of style with css.
First, we will want to arrange the HTML a bit to support our controls being rendered to the right of the grid rather than below. This could be done with css, but for the purpose of simplicity, we will do it with a good old fashioned table.

<table>
	<tr>
		<td rowspan="2">
			<div id="container">
				<canvas id="grid">
					<p>Your browser does not support HTML5 canvas</p>
				</canvas>
			</div>
			<script type="text/javascript" src="scripts/grid.js"></script>
		</td>
		<td>
			<!-- controls -->
		</td>
	</tr>
</table> 

Instead of using buttons, to improve the appearance, we will use images for some of the controls. For the pen size selection, I chose to use text. For this, you can simply open up your favorite image editor (I chose gimp), select your preferred font, type in your label and save the image. For the other controls, you can simply use google to find images available for free via the creative commons license.
Once you have selected the images, all that is required is to change the input type of the elements from button to image and add a source path. I’ve created an images folder for this purpose, but you can place them anywhere that you choose.

<div><input type="image" src="images/eraser.png" title="erase" onclick="setEraser()" ></div>

If you remember from last week, we were using the mousedown event on any button other than mouse button one to provide the eraser functionality. To make it more intuitive, a control has been added to provide that functionality instead.
The process of choosing colors by defining a button or image input per color as we did last week isn’t very scalable. To solve this problem, we will add a color selector to the the controls section. We’ll discuss the implementation a bit later, but will define the element while working with the html.

<input type="color" id="colorpicker" name="colorpicker" /> 

Now that we have all of the controls defined, the html table should look similar to the following.

<td rowspan="2">
	<div id="container">
		<canvas id="grid">
			<p>Your browser does not support HTML5 canvas</p>
		</canvas>
	</div>
	<script type="text/javascript" src="scripts/grid.js"></script>
</td>
<td>
	<div><input type="image" src="images/smallPen.png" title="small pen" onclick="setPenSize(2)" ></div>
	<div><input type="image" src="images/mediumPen.png" title="medium pen" onclick="setPenSize(4)" ></div>
	<div><input type="image" src="images/largePen.png" title="large pen" onclick="setPenSize(8)" ></div>
	<div><input type="image" src="images/eraser.png" title="erase" onclick="setEraser()" ></div>
	<div><input type="image" src="images/trash.png" title="clear" onclick="initCanvas()" ></div>
	<input type="color" id="colorpicker" name="colorpicker" />
</td> 

Last week, our canvas used a blue background color so that it was clearly visible on the page. To improve the appearance, we will use a white background and use css to define a border. To do this, create a folder called css and an empty text file within it named grid.css. Then simply use the following to create a nice border around the canvas

#container {
	width: 400px; margin: 0px 12px 24px 12px;		
	box-shadow: 0px 5px 25px #343434;
	-moz-box-shadow: 0px 5px 25px #343434;
	-webkit-box-shadow: 0px 5px 25px #343434;
	-webkit-border-radius: 10px;
	-moz-border-radius: 10px; 
	border-radius: 10px;
}

Next, add a reference to the css script in the head section of the page.

<link rel="stylesheet" href="css/grid.css" type="text/css">

The last step is to implement the color picker functionality. Rather than re-inventing this functionality, we will use the fantastic color picker called Spectrum from Brian Gridstead. After evaluating several freely available color picker controls, Spectrum proved to be far and away the easiest to implement, most compatible with all of the major browsers, and feature complete.
The first step in implementing Spectrum is to download spectrum.js and spectrum.css. I’ve placed them in the scripts folder and the css folder respectively. Once the files are in place, add them to the page.

<script src="scripts/spectrum.js" type="text/javascript"></script>
<link rel='stylesheet' href='css/spectrum.css' type="text/css">	

And finally, bind the extension to the “colorpicker” element that we defined earlier while creating the controls section. To do this, simply add the following to grid.js .ready function.

$("#colorpicker").spectrum({
	color: "#0000ff",
	change: function(color) {
		penColor = color.toHexString();
	},
	show: function(color) {
		erase = false;
	}
});

As you can see, the change event of the color picker sets our pen color and the show event disables the erase functionality. Be sure to spend some time reviewing the excellent documentation provided on the Spectrum website to learn more about all of the options available with the extension.
For now, we have completed our face lift for the drawing application. The full source code is available via the demo.

June 5, 2012

A simple drawing grid with HTML5 part 2

Last week we created a full page drawing surface with HTML5 canvas. This week we will add a few simple controls to allow for the user to clear the surface, set drawing colors, and choose different sizes for the ‘pen’. Next week, we will finish the simple drawing application with a bit of css styling.
To make room for some controls, the drawing surface will no longer encompass the entire page. Instead of a fixed width, we will still scale the size by a factor of one half x and y.

var viewWidth = window.innerWidth * 0.5;
var viewHeight = window.innerHeight * 0.5;

If you remember last week, we relied on window events for clearing and initializing the canvas. Since we will be adding a button for clearing the canvas, the window events are no longer required. Instead, we will initialize the canvas when the page has been loaded.

$(document).ready(function() {
	
	initCanvas();

	$("#grid").mousedown(function(e) {
		mouseDown = true;
		mouseButton = e.which;
	}).bind('mouseup', function() {
		mouseDown = false;
	}).bind('mouseleave', function() {
		mouseDown = false;
	});
	
	$("#grid").mousemove(function(e) {
		if (mouseDown) {
			var x = Math.floor((e.pageX-xOffset) / penWeight);
			var y = Math.floor((e.pageY-yOffset) / penWeight);
			if (x != lastX || y != lastY) {
				lastX = x;
				lastY = y;
				ctx.fillStyle = mouseButton == 1 ? penColor : backgroundColor;
				ctx.fillRect(x*penWeight, y*penWeight, penWeight, penWeight);
			}
		}
	});
});

The one important change to this scripting is that we have added a bind for the ‘mouseleave’ event. This is required since the canvas no longer covers the entire page.
The canvas initialization scripting should be separated as it also provides the functionality of clearing the canvas by clicking on a button.

<input type="button" value="Clear" onclick="initCanvas()" >
initCanvas = function() {
    grid_canvas.setAttribute("width", viewWidth);
    grid_canvas.setAttribute("height", viewHeight);
    grid_canvas.style.top = 0;
    grid_canvas.style.left = 0;
	
	ctx.clearRect(0,0,viewWidth,viewHeight);
	ctx.fillStyle = backgroundColor;
	ctx.fillRect(0,0,viewWidth,viewHeight);	
};

Similarly, some buttons will be added to allow the user to specify the drawing color and drawing size.

<input type="button" value="Red Pen" onclick="setPenColor('rgb(255,0,0)')" >
<input type="button" value="Small Pen" onclick="setPenSize(2)" >
setPenColor = function(rgb) {
	penColor = rgb;
};

setPenSize = function(size) {
	penWeight = size;
}

So now we have a more useful drawing application that gives that provides some expected functionality. The results will still be fairly primitive, but we will work on improving the presentation next week with some css styling.

The complete source can be found by viewing the source of the demo.

Tags: ,