When programmers face a problem they have already solved before, they usually rely on code reuse, and obviously, on their own previously acquired software knowledge, to
build new software. As software development becomes mature, the code reuse routine often becomes a more standardized process which includes techniques, collections of implementations
and abstractions such as software libraries, design patterns and frameworks, so that other people in the developer's team can take advantage of the common knowledge/code implementation reuse.
When it comes to JavaScript development, the presence of the ubiquitous jQuery library can sometimes lead to the development of plugins,
which are a broader kind of code reuse, because they can be made public and help a much wider developer community.

This article approaches two separate and very distinct programming capabilities: the first one is the ability to design your own jQuery plugin (that is, extending the
usefulness of the jQuery's dollar sign) and the other is the art behind drawing your own 3D bar charts, using already existing free libraries, without relying
on third party tools.

The goal of the article is not to provide a 100% professional, flawless 3D charting tool, nor a ultimate jQuery plugin, but instead it tries to give you a direction
on how simple things can be made using simple tools.

This article contains the code needed to run a website relying no programming languages other than JavaScript, and consequently without references to assemblies or C# code,
so it doesn't need to be compiled. All you need is a development environment to run websites, such as Visual Studio or
Visual Studio Express 2012 for Web.

When developers reach the point where they decide to write a jQuery plugin, probably they are wanting not only to abstract functionalities and reuse the code, but they also want
to share some useful code with the jQuery developer community. But there is also the case when you decide to create your own jQuery plugin as a programming exercise. Whatever the case may be,
keep in mind that there are some guidelines which are worth following, in order to be successful, save time and avoid bad surprises. Begin small, keep your code in line with the best practices
and improve it as you code. You can learn more about jQuery plugin best practices by reading it in jQuery's Plugins/Authoring documentation page.

We must start by creating a immediately-invoked function expression (IIFE) in JavaScript code. The IIFE is a design pattern that provides the self-containment of
private functions variables and functions within the plugin scope, thus avoiding the pollution of JavaScript's Global Environment. JavaScript developers will easily recognize
the IIFE pattern by the following code:

(function(){
/* code */
}());

In the above code, the outermost pair of parentheses wrap the function in an expression and immediately forces its evaluation. The pair of parentheses in the last line of code invokes the function immediately.

When it comes to jQuery plugin development, it's important to pass the jQuery reference as a parameter in our IIFE expression, so that the dollar sign ($) can be used safely within the scope of the plugin, without
the risk of external libraries overriding the dollar sign:

(function($){
/* jQuery Plugin code goes here. Notice the $ sign will never have a meaning other than the jQuery object. */
}(jQuery));

Next, we create the function that will hold and execute the whole of our bar chart plugin functionality. Notice the options parameter,
which will contain all the initialization settings needed to configure the bar chart according to the bar chart requirements:

Inside the plugin function, the context is given by the this JavaScript keyword. Most often than not, developers will be tempted to
reference the context by enclosing it using the dollar sign (i.e. jQuery) function: "$(this)", instead of just this. This is a common mistake,
since the this keyword already refers to the jQuery object and not the DOM element inside which the bar chart is being created:

In the above JavaScript code, we are storing the value of the this object in the self reference. This is needed specifically inside functions,
where the this keyword behaves as the context for the function itself, instead of the context for the outermost plugin function. Thus, the self will
be used as the context for the bar chart plugin instead.

The plugin code starts by defining a series of settings that will become the default values for the most common configurations. This will provide our plugin users
with convenient standard values that can be either configured (allowing a flexible charting component) or ignored (so that the plugin user can provide the smallest set
of startup configuration).

As the plugin component gets more sophisticated, it's generally a good idea to provide a more complete and comprehensive set of default settings, in order to give
users a powerful, flexible and unobtrusive plugin.

The Html5 Bar Chart plugin relies heavily on the awesome Paper JS library. PaperJS was developed by Jürg Lehni and Jonathan Puckey
and is an open source HTML5 library for vector graphics scripting,
which runs on top of the HTML5 canvas element, exposing a powerful programming and well designed interface. PaperJs is compatible with Scriptographer, a scripting environment
for Adobe Illustrator with more than 10 years of development.

Since HTML5 Bar Chart needs the PaperJS, which in turn need the Canvas element, it would be reasonable that we required the user to provide a HTML5 Canvas element in order to build the bar chart. But instead,
the bar chart plugin is called on an ordinary div element, and the very bar chart plugin creates the canvas element. Of course, here we are using the standard jQuery DOM element creation syntax. Notice
the last line in the following code snippet, where we append the newly created canvas element to the target DOM div element (referenced by the this keyword):

By default, when you start using Paper JS, the library automatically creates a new so-called "Paper Scope", that is, a scope object that is bound to the canvas on which
Paper JS will render the graphics. This default scope is provided by the paper instance. But since we may need to create multiple charts (bound to multiple canvasses)
in the same page, we should create one PaperScope per chart. The following line generates a brand new instance of PaperScope:

We render the bar chart title by defining a new PointText object containing the title as configured in the initial bar chart settings. Some adjustments are needed for the
chart title, such as defining the layout as center-justified and positioning it at the horizontal middle point of the canvas view.

Most of the elements of the bar chart will gravitate around the point where both the horizontal and vertical axes cross, therefore it is convenient to define a variable with
an object that holds the zero point coordinates. Notice that the margins are discounted in the calculation.

Since bar charts are about comparison of numbers, it's clear that rendering the value bars will only be possible if all values are taken into consideration. That is,
we should first discover the maximum and minimum discrete values from our data array, and only then will we be able to render the bars properly:

Depending on how big the numbers are, we may end up with a cluttered mess of numbers in our bar chart. Fortunately, the magnitude variable is up to the task
of simplifying the data visualization by cutting the numbers by thousands, millions, and so on, making the bar chart more pleasant to read and clear to understand.

In the cases when the resulting re-scaled maximum value ends up with too many digits, it would be a problem to show it correctly. That's why
a rounding method is used, so that it doesn't end up with an excessive number of digits.

With all the numbers correctly re-scaled, we now must write all the scale values (arbitrarily defined as 5 distinct values) alongside the scale line, beginning
with zero and ending with the max scale value. Again, a PointText object is instantiated, and then positioned at the left side of the scale line.
Each scale value must be rounded so that it doesn't have excessive number of digits.

At the left margin, we place the caption that will explain what the discrete values are about. Notice that the instance of PointText is
rotated by 270 degrees, which means the text is flowing from the bottom to the top of the chart.

Alongside the caption with the discrete values caption, there is the caption for the magnitude of the values. This is needed so that the user doesn't mistake
the scale numbers by the captions only, but also take the magnitude in consideration.

Now we use once again a new instance of the PointText to render the category names below the horizontal bottom line. Notice that, for the
sake of saving space in our chart, the category names are rotated by 270 degrees, which means that the text is now flowing from the bottom to the top of the chart.

When the bar chart is first shown on the canvas element, instead of just pushing a static image of the chart, we initiate a nice animation, where each bar starts at
the height zero and grows until it reaches its defined height. This functionality would most likely have a low priority in any project, but it adds an interesting visual
effect that captures the user attention to the data being displayed, in a professional way.

It would be a reasonable decision if we treated the category bar as an object. That is, each bar would have to be initialized, and would have
predefined properties and methods. But instead of creating a brand new object from scratch, we extend the Paper JS Group object.
The Group object is a collection of items, and this kind of Paper JS object is particularly useful for our category bar objects,
because the underlying Group object can hold the 3 visual components of the bar: the front face, the top face and the left face.

As expected, the initialization of the html5Chart.Bar will take in the basic settings needed to render the bar. As we will see later on, the categoryName,
and originalValue properties are used to render the caption balloon with category data that is shown as the user moves the mouse over the bar. The zeroPoint
provides the y coordinate that represents the bottom line for the bars. The middleX is the horizontal offset representing the middle position of the bar region.
The dataItemBarAreaWidth is the amount of space allocated for each bar. The parameter barHeightRatio is the pixel/value ratio that was previously
calculated based on the maximum discrete value. Finally, the depth3DPoint is the pair of coordinates measuring the offset distance regarding to
the top right position
of the front facing side of the bar. Next, The cardinal points in the point codes indicate the position of the points regarding to the bar.

Another interesting fact about the initialization function is the color scheme. Since we are rendering 3D bars, they would appear unrealistic if we painted every side of the bar with
the same color. So it would be nice if we adjusted the RGB (red/green/blue) components of the color in order to create light/darker effect in the 3D bar. Parsing the RGB components
from a hexadecimal color value is relatively simple, as we see by the code snippet below. But the problem gets harder when the user provides named colors for the bars. In this case,
the colourNameToHex (obviously) converts hard-coded color names into their hexadecimal counterparts, using a simple
dictionary.

Finally, the children collection property of the underlying Group object is initialized, and then the 3 sides of the bar (created as Path objects)
are added to the children of this group.

Another nice feature of the HTML5 bar chart is the floating caption pop up that appears whenever the user moves the mouse over one of the bars. The caption
displays the category name and the discrete value. In our code, the pop up functionalities have been encapsulated as an extension of the Group
object.

When the user moves the mouse over the bars, the pop up is displayed. When the mouse leaves the bar area, the pop up is hidden. This functionality is
possible thanks to the tool.onMouseMove function of Paper JS, along with another Paper JS function (paper.project.hitTest)
that tests the mouse position against the bar objects already present in the chart.

Whenever the user clicks over a category bar area, the bar chart plugin responds by returning both the category name and the value of that category. Of course,
the onDataItemClick callback is only invoked if the user have previously subscribed to that event callback.

This article summed up the basic techniques needed for developing bar charts (as well as other types of graphic tools) using jQuery plugin and
the Paper JS
library. I hope the article's explanation is reasonably clear, and in any case it remains open for future improvements.

Thanks for the reading, and please feel free to express your opinions regarding the article and/or the accompanying code.

Share

About the Author

Marcelo Ricardo de Oliveira is a senior freelance software developer who lives with his lovely wife Luciana and his little buddy and stepson Kauê in Guarulhos, Brazil, is co-founder of the Brazilian TV Guide TV Map and currently works for ILang Educação.