WebReference.com - Drawing Charts with JavaScript (2/7)
[previous] [next] |
Drawing Charts with JavaScript
Getting Started
Ok, most of you caught me. I actually used two images on the previous page. Two 1-pixel gifs that are 44 bytes each. We can use 20 different colors for our charts and still remain under 1k!
The trick to drawing charts involves a few steps:
The very first thing we need to know is what the HTML for the chart will look like. The technique we will use involves dynamically building an HTML table that will hold our images. For a horizontal bar graph, this means a new table row for each bar that we will draw. Each row in our table will have two cells. The first cell will show the student name, while we use the second cell to draw the bar for our chart. We'll give the table a gray background color to make it stand apart from the rest of the page.
Next we stretch our images to the desired width for each bar. The key to drawing bar charts is to set each value that we intend to plot, as a proportion of the largest value that we will plot, and then to multiply that by the overall width of the chart. Then we simply stretch our one pixel image to that width. Easy, no? Then consider the actual formula:
widthOfBar = valueToPlot / highestValueToPlot * widthOfChart
We'll need to know the highest value that we're going to plot, the overall width that we want our chart to be and, quite obviously, the given value that we are going to plot right now.
Each bar in our chart will represent one student's test score. We'll store the student scores in a JavaScript array, and the name of the students in another array, being careful that the first element in the student array corresponds with the first element in the scores array and so on. Since we need to know the largest value that we will be plotting, we'll create a variable called
maxValue
and iterate through our scores array, comparing each member of the array tomaxValue
. If we find a value in the array that is greater thanmaxValue
, we'll assign it tomaxValue
.Finally, we'll walk through our arrays, building the HTML to output to the page for our chart.
Here's what the HTML for our chart might look like (if we were plotting only two students):
<table bgcolor="#cccccc" cellpadding=0 cellspacing=2 width=355><tr><td>
<table bgcolor="#cccccc" cellpadding=0 cellspacing=2 width=355>
<tr>
<td>John</td>
<td><img src="red.gif" width=250 height=10 hspace=2></td>
</tr>
<tr>
<td>Mary</td>
<td><img src="yellow.gif" width=270 height=10 hspace=2></td>
</tr>
</table>
</td></tr></table>
Notice that we have nested two tables. This is to prevent Netscape 4.x from showing lines between our table cells.
Note too, that we have set a width of 355 pixels for the table, even though, as you will see next, the plottable area of the chart is specified as 275 pixels wide. This is to accommodate the <td> that will hold the student's names. We'll also alternate bar colors for each row in our table.
At this point, let's look at the entire script to make the chart on the previous page. We'll put in plenty of comments to walk us through:
<script><!--
// Even though they are only 44 bytes, let's preload our images
imRed = new Image();
imYellow = new Image();
imRed.src = "red.gif";
imYellow.src = "yellow.gif";
strImage = ""; // used for alternating colors
strToWrite = ""; // We'll dynamically build a table to hold
// our chart, then write it to the screen when ready
// Store the student scores, and their names
arScores = new Array(90,100,78,86,52,99,99,100);
arStudents = new Array("Alan", "Bob", "Joe", "Mary", "Dunce", "Sally", "Allison", "Jacob");
chartWidth = 275; // the width of the chart
maxWidth = 0;
// now find the maximum value to chart
for(i = 0; i < arScores.length; i++) {
if(arScores[i] > maxWidth)
maxWidth = arScores[i];
}
// start building the output string
strToWrite += "<table bgcolor='#cccccc' width=" + (chartWidth+80) + "><tr><td>";
strToWrite += "<table bgcolor='#cccccc' width=" + (chartWidth+80) + "><tr><td>";
// continue building the HTML to output
// by looping through our arrays
for(i = 0; i < arScores.length; i++) {
if(i % 2 == 0) // alternate images by using the modulus operator
strImage = "red.gif";
else
strImage = "yellow.gif";
strToWrite += "<tr><td align=right>" + arStudents[i] + "</td>"
strToWrite += "<td><img src='" + strImage + "' width=" + parseInt((arScores[i] / maxWidth) * chartWidth) + " height=10 hspace=2>" + arScores[i] + "</td></tr>";
}
strToWrite += "</table>";
strToWrite += "</td></tr></table>";
// -->
</script>
I've bolded the formula for drawing bar charts above. This formula, in any language, is what makes drawing this type of chart possible.
Now, wherever we want the chart to appear in our page, we can simply write out the value
strToWrite
. This will work in Version 3 browsers and up.
<html>
<body>
<script><!--
document.write(strToWrite);
// -->
</script>
</body>
</html>
Got it? Good. Let's look at a vertical bar chart and then start getting interactive.
[previous] [next] |
Created: March 6, 2002
Revised: March 6, 2002
URL: https://webreference.com/programming/javascript/charts/2.html