r. alexander milowski, geek

Graph2D Javascript Library

Introduction

Graph2D is a javascript library that lets you embed interactive graphs using the HTML canvas element. The following is a simple example using 2x2 + 3x + 2, sin(x), and tan(x):

The graph can be zoomed via the '+' and '-' buttons, panned by mouse drags, reset, and redrawn. On the iPhone or Android phones, you'll need to use to clicks to pan the graph as neither supports mouse click-drag actions. The direction and distance between the clicks has the same effect as a mouse click-drag between the two points.

Using this library is simple and only requires a few steps:

  1. Add a script to the head element of your HTML document:
    <script type="text/javascript" src="http://www.milowski.com/math/graph2d/graph2d.js"></script>
    
  2. Add your graphs by adding an HTML div that encodes the functions, canvas size, and other options:
    <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='controls'>
          <span class='zoom'> </span>
          <span class='redraw'> </span>
          <span class='reset'> </span>
       </div>
    
    </div>
    
    The canvas width and height attributes control the graph size. Each function is then encoded by a separate div element. Note how the color is picked up by the style of the respective div element. Finally, the controls for the graph are displayed if you provide the controls classed div.

Currently, the functions are expressed in Javascript expressions using the variable x. Javascript does not support "normal" math expressions like x2 and instead you have to use explicit expressions like x*x. You can also use the Javascript Math object to call functions like sine (e.g. Math.sin(x)).

By default, the library is invoked on document load and scans the entire document. If you wish to turn this off, you need to modify the source and set Graph2DFactory.autodetect to false. You can then invoke the auto-detection however you want. That is, on the body:

<body onload='Graph2DFactory.detect()'> ...
or use event handlers
window.addEventHandler('load',function() { Graph2DFactory.detect(); }, false);

Not working for you? This graphing library relies on the HTML canvas element and that isn't supported by Internet Explorer. Please try Firefox, Safari, Chrome, or Opera. It should also work on your iPhone or Google Android-based phone.

Demonstation Page

A demonstration of the use of the Graph2D library.

Source

The current version of the Graph2D javascript library.