r. alexander milowski, geek

MAA Session 2010 - Graph2D: An Interactive Graphing Library using the HTML Canvas

API Example

Javascript API

  • There is a full Javascript API.
  • You can create or manipulate graphs without using the microformat.
  • This is useful for dynamic content.
  • For example, detecting graphs in added content:
    Graph2DFactory.detect(myNewDiv);

The Magic Incantation

  1. Add a script header to include the Graph2D code:

    <script type="text/javascript" 
            src="http://www.milowski.com/math/graph2d/graph2d.js">
    </script>
    
  2. Add an onload event handler to detect the graphs:

    <body onload='Graph2DFactory.detect()'> ...
    

    or use event handlers

    window.addEventHandler(
       'load',
       function() { Graph2DFactory.detect(); }, 
       false
    );
    

The Graph2D Microformat

  • A simple "microformat" on an HTML div:
    • class="graph2d" on the div wrapper,
    • each function is a div with class="function",
    • control panel is a descendant div with class="controls",
    • control buttons are spans with class of "zoom", "redraw" or "reset".
  • The microformat is "loose".
  • You can place these anywhere within the wrapping "graph2d" div.

A Simple Example

2*x*x + 3*x + 2
Math.sin(x)
Math.tan(x)
<div class='graph2d'>
   <canvas width='500' height='500'><!--canvas--></canvas>
   <div class='function' 
              style='color: rgb(255,0,0);'>2*x*x + 3*x + 2</div>
   <div class='function' 
              style='color: rgb(0,0,255);'>Math.sin(x)</div>
   <div class='function' 
              style='color: rgb(0,255,0);'>Math.tan(x)</div>
   <div class='controls'>
     <span class='zoom'> </span>
     <span class='redraw'> </span>
     <span class='reset'> </span>
   </div>
</div>

For More Information

  • Works in Safari, Firefox, Chrome, iPhone/iPod Touch, Google Andriod phones ...
  • IE 8 is still to come (possible but not attempted).
  • Examples, code, and documentation at:
    http://www.milowski.com/math/graph2d/
  • Contact me at:
    alex@milowski.com

What is Graph2D?

  • A Javascript library for 2D graphing of functions that provides:
    • multiple graphs,
    • axes and grids,
    • zooming and panning;
  • a simple "microformat" inclusion mechanism,
  • a programming API for the "brave",
  • and all using the new HTML5 canvas element.

Graph2D: An Interactive Graphing Library using the HTML Canvas

R. Alexander Milowski