WebReference.com - Drawing Charts with JavaScript (3/7) | WebReference

WebReference.com - Drawing Charts with JavaScript (3/7)

To page 1To page 2current pageTo page 4To page 5To page 6To page 7
[previous] [next]

Drawing Charts with JavaScript

A vertical bar chart:

The obvious difference here is that we are stretching the one pixel gif vertically rather than horizontally. Of course, we are stretching it both ways in either situation, as I have arbitrarily set a width of 16px for the bars (height of 10px in the horizontal version). Set yours to whatever values suit you. Here is what is done differently for a vertical bar chart:

I'll show the code for the vertical bar chart, but we won't delve into any detailed discussion, as the concept is exactly the same. Key differences will be highlighted in red:

<script><!--
imRed = new Image();
imYellow = new Image();
imRed.src = "red.gif";
imYellow.src = "yellow.gif";
strImage = "";
strToWrite = "";
arScores = new Array(90,100,78,86,52,99,99,100);
arStudents = new Array("Alan", "Bob", "Joe", "Mary", "Dunce", "Sally", "Allison", "Jacob");
chartHeight = 275;
maxHeight = 0;
for(i = 0; i < arScores.length; i++) {
 if(arScores[i] > maxHeight)
    maxHeight = arScores[i];
}
strToWrite = "<table bgcolor='#cccccc'><tr align='center'>";
for(i = 0; i < arScores.length; i++) {
  if(i % 2 == 0)
     strImage = "red.gif";
  else
     strImage = "yellow.gif";
  strToWrite += "<td valign=bottom>" + arScores[i] + "<br>";
  strToWrite += "<img src='" + strImage + "' height=" + parseInt((arScores[i] / maxHeight) * chartHeight) + " width=16 hspace=2></td>";
}

strToWrite += "</tr><tr>";
for(i = 0; i<arStudents.length; i++) {
 if(i % 2 == 0)
    strToWrite += "<td width=16>" + arStudents[i] + "</td>";
 else
    strToWrite += "<td width=16><br>" + arStudents[i] + "</td>";
}
strToWrite += "</tr></table>";
 
// -->
</script>

The last block of code in red is to add a <br> tag to every other student name in the bottom <tr> to create an offset, making our chart more readable, without stretching the table so wide that the viewer loses the relational perspective of the bars in the chart. For the sake of demonstration, let's give the table a 1-pixel border, to better get an idea of what we've drawn:

Ok, so now we've seen that we can draw bar charts with relative ease. What will make it interesting and fun for your audience is when they get to draw the charts. So let's make this thing interactive!


To page 1To page 2current pageTo page 4To page 5To page 6To page 7
[previous] [next]

Created: March 6, 2002
Revised: March 6, 2002

URL: https://webreference.com/programming/javascript/charts/3.html