Javascript Pie Chart

Here is a bare-bones pie chart script, useful for decorating a web page with live data from a CGI script. This works in modern browsers that support the CANVAS tag, and avoids loading Java.

Pie Chart using CANVAS Tom Van Vleck 2010

Put two lines in the HEAD section of your page like so (the second line is needed to make Microsoft Internet Explorer work):

<script type="text/javascript" src="piecanvas.js"></script>
<!--[if IE]><script type="text/javascript" src="excanvas.js"></script><![endif]-->

Create a chart like this:

<canvas id="canvas2" width="200" height="220" title="title attribute">
  <table id="mydata2" class="datatable">
    <caption>Pie Chart using CANVAS</caption>
    <caption>Tom Van Vleck 2010</caption>
<script type="text/javascript">piechartcanvas('mydata2','canvas2','#ccffaa', 1);</script>

The arguments to piechartcanvas are the ID tag of the data table, the ID tag of the canvas, an optional background color in hex, rgb(), or as a color name, and an optional flag for the data label format: label format 0 uses the label as specified; label format 1 uses "xx% label". (Each ID tag should be unique in your HTML page.)

Pie wedges displayed clockwise from 12:00. Wedges with less than 2% of the total will not be labeled. You can specify the color for the pie wedges as hex, rgb() or color name, by providing a third column in the data table, as shown above. If you don't specify the color for the pie wedges, the script chooses colors, and the first wedge will be green. The first CAPTION tag is the chart title; subsequent CAPTION tags are concatenated into the bottom title. If Javascript is disabled or CANVAS is not supported, the data will be displayed as a table; you can put a CLASS attribute on the TABLE and CANVAS tags to apply CSS styles if you wish to.

(3/18/11: When Microsoft Internet Explorer 9 came out, it didn't display the chart. One way to make it work is to change the DOCTYPE at the top of the file to

  <!DOCTYPE html>

.. although this may cause issues with making the code display correctly in older browsers. I also had to make a minor change to piecanvas.js because the CANVAS tag in MSIE 9 works differently from the CANVAS tag in Firefox: in IE9, if there is text inside the CANVAS tag it is displayed after the graphic; in Firefox, text inside the CANVAS tag is treated as "fallback content" and is not displayed if the graphic is rendered. I changed the code for piechartcanvas() to hide the data table if it displayed the chart.)

(6/22/17: Added some code to handle "High DPI" displays. If your display has more than 96 device pixels per inch, the function draws a chart with more pixels and tells the browser to scale it. Tested in Safari, Firefox, and Chrome.)

Here are links to the source files. Feel free to improve on my code.

Written 12/12/2010