Interactive SVG with JSXGraph


Table of Contents

JSXGraph as a web viewer for dynamic geometry software
Currently supported file formats
Constructing from scratch
Turtle graphics
Turtle graphics in mathematical modelling
Drawing with turtle graphics
JSXGraph as a front end to server side applications
Plugins for integration in other web applications
Implementation details
Cross-browser development
HTML elements
Speed improvements

JSXGraph[1] is a client-side web application/library for advanced vector graphics in a web browser. Its range of applications starts from the display of simple bar charts and pie charts up to the interactive display of function graphs and geometric constructions used in schools and universities. Even more advanced features of JSXGraph are the on-the-fly solving of Differential Equation Systems, the display of Lindenmayer systems[2], which are of importance in Biology, and dynamic computation of regression polynomials.

JSXGraph is a library which may be used in various situations. The main application is to serve as a client-side viewer for educational mathematics in schools and universities. Usually these constructions, especially from euclidean geometry, are available in different proprietary XML based file formats, and are intended to be displayed by their associated Java applet. In order to compensate the slow demise of Java applets in the web browsers, JSXGraph may prove to be valuable. At the moment JSXGraph supports the file format of GEONExT[GXT], Intergeo[I2GEO], and - at least partially - GeoGebra[GGB]. Since JSXGraph comes with its own implementation of unzip and gunzip, it should be easy to adapt JSXGraph to a whole variety of even more file formats.

Beside using it as a viewer for existing material, the JSXGraph library may be used as an API for advanced special purpose visualizations. JSXGraph enables interactive experiments with sophisticated mathematical problems in the web browser. One example is the simulation of the epidemiology model for the swine flu[3]. The possibilities of JSXGraph in this respect exceed by far the options offered by software which is common in schools today.

Another possible application is to use it as a front end for server based applications. One example is the widely-spread free statistics software R[R]. After the mouse up event is fired in this application, the coordinates of the points are sent via AJAX to the R interface on server side. After doing some computations in R, the web server sends the results back to the browser. There the display is updated by JSXGraph. A more simple application of JSXGraph can be the creation of charts on server side. For example PHP could be used to generate JSXGraph charts which are sent to the web browser. Hence the high quality of the vector graphics display can be fully exploited. The additional overhead of downloading JSXGraph is less than 100 kByte, which is smaller than most bitmap images. Furthermore, the JavaScript source is static and can be cached by the browser, which is not possible with non static chart pictures.

From a technical point of view, JSXGraph is implemented in JavaScript. It generates SVG output on Mozilla-, Webkit-, and Presto-based browsers, and VML on the Internet Explorer. Therefore, JSXGraph runs on every modern browser.

JSXGraph is open source software, released under the Lesser GNU General Public License (LGPL). The source code is hosted by sourceforge.

The originally intended purpose of JSXGraph was having a JavaScript library for displaying geometric constructions in a web browser. So it is possible to visualize geometric elements that are taught in schools and universities like points, lines, circles, arcs, and angles, as well as predefined composition elements like orthogonal lines, midpoints, and triangles. JSXGraph not only provides tools for displaying geometric constructions but also for doing calculus like plotting curves starting from function graphs with tangents up to parametric and polar curves, cubic splines or other interpolation methods.

Dynamic geometry software (DGS) are computer programs which allow one to create and then manipulate geometric constructions, primarily in plane geometry. In most DGS, one starts a construction by putting a few points and using them to define new objects such as lines, circles or other points e.g. intersections of lines and circles. After some construction is done, one can move the points one started with and see how the construction changes.

There are lots of different available software packages to play around dynamically with geometry. Most of them are written in Java, such as GeoGebra, Cinderella[CDY], Compass and Ruler[CaR] or GEONExT, others like The Geometer's Sketchpad[TGS] or Cabri[CABRI] offer a Java based web viewer. If you want to integrate a construction that was created with one of these DGS in a web page, it takes some time to load the corresponding Java applet before you can use it. There are moreover big doubts about the future of Java in web browsers because Java applets are vanishing more and more from the internet and are actually not supported in browsers on modern mobile internet devices. As a result, the idea of JSXGraph was to read GEONExT Files and display them in the browser using JavaScript to manage the DOM elements of SVG or VML, depending on what browser is used. JavaScript is furthermore used to realize the dynamic part in DGS by capturing the browser's mouse events.

The JSXGraph API used in the readers for the different file formats can also be used to create a construction from scratch or to manipulate a construction loaded from a given file. JSXGraph contains functions for compass and ruler constructions in euclidean geometry basing on points, lines, circles, arcs, and angles. Those can be intersected or combined in predefined ways. For example one can construct a line that is parallel to another one or a point that is the midpoint between two other points by using integrated JSXGraph methods. Additionally, one can easily implement own composition elements with JavaScript and the above-mentioned functions.

Beyond the capabilities of JSXGraph with regard to geometric constructions, one is also able to visualize calculus. The possibilities start from plotting simple function graphs to displaying more complex graphs like parametric and polar curves which can be analyzed using the implemented methods for tangents, integrals or spline interpolation.

With an implementation of the explicit Runge-Kutta method, JSXGraph can also be used to solve ordinary differential equations numerically on the fly with the possibility to change the parameters on runtime and watch the results.

Turtle graphics as a method of drawing offer a wide variety of applications. So JSXGraph provides an easy-to-use interface to them.

Mathematical modelling with differential equations can also be done using turtle graphics. Exponential population growth models can be simulated easily by using the discrete analogue of the corresponding differential equation and computing the movement of the turtle in equidistant small time intervals.

In a similar way, logistic or autocatalytic population growth processes can be modelled. A further application which can be simulated with turtle graphics is epidemiology where a set of differential equations is given to predict the immediate consequences of a epidemic like the Hong Kong flu or the swine flu. With only a few lines of code the chronological sequence of the rate of susceptible, infected and recovered population can be studied.

An advantage of using turtle graphics is the easy way to draw. The basic commands are "Go forward a given number of units" and "Rotate left resp. right a given angle". The following programm listing draws "SVG" shown in the picture below.

The rt(), lt(), fd(), and bk() methods are abbreviations for right(), left(), forward(), and back(). A full list of commands can be found in the JSXGraph wiki[7].

var t = board.createElement('turtle');>
// Draw the S,
t.rt(90); t.fd(100);; t.fd(100);; t.fd(100); t.rt(90); t.fd(100); t.rt(90); t.fd(100);
// the V, and
t.rt(70); t.fd(210);; t.fd(210);
// the G
t.rt(70); t.fd(100); t.bk(100); t.rt(90); t.fd(200);; t.fd(100);; t.fd(100);; t.fd(40);

Example 5. Drawing "SVG" using a turtle.

This approach can be used to easily produce beautiful Lindenmayer systems like plants or penrose tilings which are known from chaos theory . Similarly, well-known fractals like the sierpinski triangle or the Koch snowflake can be drawn. Other applications can be found in statistics where one can visualize random walks with turtles.

After implementing all the geometric objects and calculus in JSXGraph it was not difficult to extend the library to support charts. For example line charts and cubic spline interpolated charts are made of function graphs, sectors are used to display pie charts, and horizontal resp. vertical bar charts are based on polygons. Of course all of the visual options from the geometric elements like fill and stroke colors, fill gradients, line styles, shadows or special highlighting effects are passed on to the charts. But also the dynamics is still available, so even interactive charts can be done with JSXGraph which is useful for forecasts with varying parameters to model different scenarios.

A pie chart on the left hand side and an interactive bar chart together with a static line chart on the right hand side

Figure 5. A pie chart on the left hand side[10] and an interactive bar chart together with a static line chart on the right hand side[11].

JavaScript enables us to use the XmlHTTPRequest object to interact with server side applications. Currently one can use our AJAX wrapper JXG.FileReader or the one provided by Prototype[12] or jQuery[13]. So JSXGraph can be used to visualize the output of server side calculations and provides new input data for server applications.

For example it is possible to fetch share prices from a web site like Yahoo finance. To do this a script on your own webserver is required because of security restrictions concerning the XmlHTTPRequest object which cannot be used in conjunction with a url that is not on the same server as the web site starting the request. After starting the script from JavaScript it sends back the data from Yahoo which then is parsed by the JavaScript and visualized using a curve.

To ease the integration of JSXGraph into other web applications we provide some plugins for a couple of them. Those are the blogging software Wordpress[15], the basis software for Wikipedia called MediaWiki[16], and the course management system Moodle[17]. The plugin for the latter one ist still experimental. The user only has to provide a few options for the drawing panel and the JavaScript construction code or a url to a file in a format supported by JSXGraph. The rest is done by the plugin, like loading the necessary files, initializing the division element containing the drawing panel and finally loading the file or the javascript construction code.

The main focus of JSXGraph lies on interactivity. The JSXGraph user should experience an immediate feedback to the dragging of points with the mouse. So, special attention has to be paid to fast reactions to mouse move and mouse up events. On the other hand we want to exploit the superb output quality of vector graphics as offered by SVG. These two controversial goals - speed versus quality - have to be balanced.

The Microsoft Internet Explorer has still the largest market share of all browsers. Since we do not want to exclude the users of the Internet Explorer we have to adapt JSXGraph to this browser as well. The Internet Explorer can not display SVG, but since 1998 Microsoft[VML1998] supports VML - vector markup language - as vector graphic language in the Internet Explorer. Early in the development process of JSXGraph we decided to implement SVG and VML drawing separately, without using one of the existing abstraction layers. The reason for that decision was performance, the existing layers were too slow at that time.

SVG and VML are similar in many aspects, but different in many details. In order to realize visual properties VML heavily makes use of subnodes of XML nodes. SVG however mostly uses attributes for the same visual properties. Therefore, the JSXGraph source contains the two files SVGRenderer.js and VMLRenderer.js which control the different graphics languages. The user working with JSXGraph should not get aware of this separation at all because all methods for accessing the drawing layer are encapsulated by JSXGraph.

For SVG drawing JSXGraph rarely uses formatting through CSS. The reason is that in the beginning of the development process the use of CSS styles consumed to much computing resources, especially setting the opacity in Firefox. So, nearly all visual properties are realized by setting attributes and applying filters. Even if filters in SVG are still not implemented satisfactorily in all browsers, JSXGraph supports shadows and gradients via filters since version 0.76. At the time of writing shadows slow down the Firefox browser considerably. Further, there seems to be a bug for horizontal and vertical lines. In these cases neither the line nor its shadow is visible. In Webkit based browsers like Chrome and Safari these filters are not implemented, yet. In Opera it looks ugly. On the other hand, VML realizes shadows as a subnode. There, no noticable speed reduction is observable.

In order to enable fast reactions to user interactions like mouse moves, JSXGraph contains many tricks to speed up the computations. Even if the JavaScript interpreters, respectively Just-in-time-compilers, have made huge progress since the development of JSXGraph has been started, special care about implementation details is still necessary. Here, we list a few of the tricks, which proved to be useful for our implementation. Of course, the benefits of most of these tricks depend on the browser implementations and may change with new versions of the browsers.

Common functions like binomial() and factorial() are realized with memoizer techniques, as descripted in [Crockford2008], page 44. Thus, the expensive computation of each value of these functions is done only once.

The JavaScript source code of JSXGraph version 0.76 consists of 20 individual files, which add up to about 980 kBytes including comments. These 20 files are bundled together in one big file which is subsequently compressed by the YUI compressor[18] from Yahoo!. During this process comments and superfluous whitespaces are removed. The resulting file jsxgraphcore.js only consists of 380 kBytes. If the web server delivering jsxgraphcore.js has DEFLATE enabled, which means it compresses its output additionally with gzip, the web browser has to download about 80 kByte. In many cases this is still less than delivering the same construction as a non-interactive PNG image.

Sometimes function graphs are expensive to compute. One example is a regression polynomial through a given set of points. On update the position of all points has to be determined, the resulting linear system of equations has to solved. Its solutions give the coefficients of the polynomial. We certainly do not want to do this computation for determining every single function value, since during every update of the function graph we have to compute more than a thousand values of that function.

We apply the following strategy: When the function graph is updated, we compute the coefficients of the polynomial only once. Then we use these coefficients for the computation of all function values. But where to store the coefficients? Using the "this" keyword does not give the desired results in a function. But fortunately, we can use the function invocation pattern, see [Crockford2008], page 28. In the example below, the function which is returned by the call of "generateFunction()" still has access to the variable "coeffs". This is based on the powerful concept of closures, which is part of JavaScript and comes from functional programming languages. So, we can compute many function values very fast, and we do not have to do the bookkeeping, where these coefficients are stored.


[2] Inspired by the work of Sam Ruby: