Introduction
This tutorial will be teaching you how to make an object in JavaScript that will allow you to make a pixel pie graph. If you don't already know what it is, you read my either
my blog post or on
Anil Dashes' Blog. You may also see a good example of a pixel pie chart at
Wired News. So we will basically try and make a pixel pie chart, something that will end up looking like this -
Pre-requisites
Before actually starting with the coding, I expect you to know very basic JavaScript JavaScript and a bit of DOM. You can go to
YUI Theater and look at all the video by Douglas Crockford.
If you have any problem during the tutorial, drop by on our
Google Group so that me or any of the other members can sort it out. I also suggest you
download the necessary file so that you'll follow better in the rest of the tutorial.
Let's Begin
So as we are going to be making a single object to take care of the whole pixel pie graph, let us take a look at what all it'll be containing.
Object Pixel Graph -
- data: This will be hash table or JSON that will contain the data that has been submitted by the user. It'll basically have a caption and a value, like "Apples, 50".
- pData: We will need to convert this data to percentages so that we can easily and efficiently. So we will be putting all the percentage values of our data into this hash table.
- colors: This'll be an array of colors from which our program will pick the colors for the pixel pie graph. We will be keeping the hex values of the colors in this array.
- title: Its always nice to have a title to the chart.
- render(): This function will actually be rendering the table of 100 X 100 where the pixel pie chart will be formed, and fill it with the right colors and values.
- validateData(): This will be a simple function to take the data and convert it to pData.
Right, now that we know what all we will be making, let us actually start building the object.
Let us start off by making our
PixelGraph object and fill it with everything we'll need. Then we'll discuss each function we need.
PixelGraph = {
data: [],
pData: [],
colors: [],
title: "Graph",
render: function() {},
validateData: function() {}
}
We'll fill the functions up later. For now let us make an instance of this object and put some data into it.
fruits = Object(PixelGraph);
fruits.title = "Sales of Fruits in 2008";
fruits.data = [
{
name: "Apple",
value: 450
},{
name: "Mango",
value:2300
},{
name: "Grapes",
value: 3700
},{
name: "Banana",
value: 1000
},
{
name: 'Cherry',
value: 2000
}
];
fruits.render("graph");
So as we see, first we make an object that'll inherit from the
PixelGraph, then we put in the title as a string. Then we add the data as an array whose elements are hash tables containing the name or caption and the value as discussed in the basic structure. Then we call the function render and pass the ID of the
div in which we would like the graph.
Now, the first function
validataData() -
validateData: function() {
this.pData = this.data;
this.total = 0;
for (var i=0; i < this.data.length; i++) {this.total += +this.data[i].value;};
for (var i=0; i < this.pData.length; i++) {
this.pData[i].value = Math.round((+this.pData[i].value / this.total) * 100);
};
}
We see that initially we give
pData the same value as
data. Then to calculate the total, we run a loop on
this.data, that has the data and take the sum of all the values and keep it in the
this.total variable. Then we run a loop on
this.pData and by using basic mathematics we take out the percentages of all the variables and keep it in this.pData.Simple as that! Now we come to the render() function. This is a lot of code so first please read it carefully and then read the explaination. Here is the code, take a deep breath -
render: function(domId) {
this.validateData();
document.getElementById(domId).innerHTML = "<h2>"+this.title+"</h2><div style='float:left' id='graph-"+domId+"'></div><div style='padding-left: 300px;' id='key-"+domId+"'><h2>Key</h2></div>";
var graphArea = document.getElementById("graph-"+domId);
var html = "<table border='1' cellspacing='0' cellpadding='0'>" ;
for (var i=0; i < 10; i++) {
html += "<tr bordercolor='red'>"
for (var j=1; j < 11; j++) {
html += "<td class='pixel-graph' bordercolor='red' id='pg-p"+((i*10)+j)+"'> </td>";
};
html += "</tr>"
};
html += "</table>";
graphArea.innerHTML += html; //Draw the table
for (i=0; i < this.pData.length; i++) {
document.getElementById("key-"+domId).innerHTML += "<p style=';color:"+this.colors[i]+"'><b>"+this.pData[i].name+"</b> <span id='key-"+i+"'> "+this.pData[i].value+"%</span></p>";
};
old = this.pData;
for (i=1; i < 101; i++) {
for (var p=0; p < old.length; p++) {
if(old[p].value !== 0) {
document.getElementById('pg-p'+i).bgColor = "#"+this.colors[p];
if(old[p].value === 1) {
document.getElementById('pg-p'+i).style.background = "#"+this.colors[p]+" url('res/new.gif') top right";
document.getElementById('pg-p'+i).style.borderTop = "none";
document.getElementById('pg-p'+i).style.borderRight = "none";
document.getElementById('pg-p'+i).innerHTML = "<p style='margin:7px 0px 0px 4px'>"+document.getElementById('key-'+p).innerHTML+"</p>";
}
old[p].value--;
break;
}
};
};
}
Right! If you haven't left the blog by now, lets start. This is where I'd say the fun part is.
- Obviously we first call the validateData() function so that we have the pData ready for when it is needed.
- Then we take the domID of the div and put a heading in it with the title and two more div's that'll contain the table of pixels and the key respectively.
- After that we run a nested loop to get the HTML code of the table that will have 10 rows and 10 columns, with each table cell having an ID of pn. Then we put this HTML into the required DIV.
- Now we'll be making another loop, that will be going through our this.pData and making the key. We associate each element of the data with a particular color. For this to function correctly we will have to fill the color array we made earlier filling it with the hex of the color. Something like ["eb088d","edadae","a83e6e", "f47d55", "d04a6f"].
- For the actual coloring of the cells we'll be running another set of loops. To understand this imagine you have a few jars of candies, each jar having different amounts of candies, with one jar containing one colored candies. You need to take each candy, jar by jar and put it in a grid of 100 X 100. So every-time you place a candy on the grid, the number of candies in the jar decreases and the number of candies in the grid increases. With that in mind read the last for loop's code again.
- We loop through the whole grid in the first loop, we sequentially check the pData to be zero (or the jar empty) and then move on to the next element(jar). Also every-time we color a cell, we decrement that elements value (because we have already taken that candy now and placed it in the grid).
If you wish to see the script in action you can download it from the
page on the
Bit Pixel Google Group. You can also drop by for any suggestions or doubts relating to the tutorials.