Share: Bookmark with delicious tweet this site Post to Facebook

RGraph: HTML5 canvas graph library - Miscellaneous documentation


 
 

Canvas fallback content and visually impaired users

When using the canvas element you should be aware of the accessibility of your graphs, for example where vision limited users are concerned. Screen readers, for example, may not be able to convert a graph into something that is reasonable, so you should consider doing this yourself, possibly using the canvas fallback content (ie the content in between the canvas tags). A possible example would be to put a table of data inside the canvas tag that the graph on the canvas represents. Doing this goes a long way towards making the data available to everyone. You might also wish to consider using the full canvas zoom or the resizing feature to enable people to enlarge the graph.


 
 

Upper and lower limits for horizontal bars

If you don't wish to specify an upper or lower limit for horizontal bars, and you just want them to extend to the upper or lower limits of the graph, whatever they may be, you can specify null for the value determining how far they extend. For cases where the X axis is in the middle and you're specifying a negative start value, or you want the bar to extend all the way to the bottom, you can simply specify an arbitrary length (eg -999999). Eg:

myBar.Set('chart.background.hbars', [[0, null, 'green'], [0,-999999,'red']]);

 
 

Setting the canvas width and height

To set the canvas width and height you must use the HTML width/height attributes and NOT CSS. If you do use CSS, the canvas will be scaled, and not enlarged, to fit the new width/height. Eg:

<canvas id="myCanvas" width="200" height="100">[No canvas support]<canvas>

For the Bar, Line, Scatter and VProgress charts you can now set the usable area of the chart with the chart.width and chart.height properties. These allow you extra space if you need it for labels. There's more details on this here.

Note: When you resize the canvas using CSS, not only will it be scaled (not enlarged), but it will also NOT be cleared. You can see this effect on the animation page with the jQuery animation example.


 
 

RGraph and older browsers

Older versions of browsers are supported (assuming they have canvas support), however, if they don't support the canvas text or shadow APIs these will naturally be unavailable. The graphs will still be drawn, though without shadows or text.


 
 

RGraph and Microsoft Internet Explorer

You can now use RGraph with Internet Explorer 8 in conjunction with ExCanvas, (which brings a degree of <canvas> support to MSIE). Bear in mind though that shadows are not available and thus are simulated. Microsoft Internet Explorer 9 has native <canvas> support. You can see some screenshots of it here.


 
 

Debugging tips

If you're having a hard time debugging your graph, try these:


 
 

Inspecting an RGraph graph

To help when debugging your RGraph graphs and canvas elements, you can use you browsers built in debugging tools. An example is the WebKit developer tools which are available in Google Chrome and Apple Safari. There is a screenshot of these tools (in docked mode) here. To view these tools in Google Chrome press CTRL+SHIFT+J. Inspect the canvas, and then the associated object can be found via the __object__ property.


 
 

Double click context menus

Windows Opera, Windows Safari, Mac Safari and Mac Firefox all attach the context menu to the double click event (left mouse button), not the right, in order to make it more reliable.


 
 

Adding your own event handlers

Because each RGraph object exposes the canvas element (the same as what you get from document.getElementById()), you can use normal procedures to add your own event handlers. Eg If you wanted to add your own onclick handler you could do this:

<script>
    var myBar = new RGraph.Bar('cvs', [7,4,2,6,3,4,8]);
    myBar.Draw();

    myBar.canvas.onclick = function ()
    {
    }
</script>

But what if, for example, you're using an RGraph feature which uses the event handler that you need? In this case you can use the standard DOM2 method addEventListener(). This will add your new event handler without replacing any existing one (ie the one installed by RGraph). For example:

<script>
    var myBar = new RGraph.Bar('cvs', [7,4,2,6,3,4,8]);
    myBar.Draw();

    function myFunc ()
    {
    }

    myBar.canvas.addEventListener('click', myFunc, false)
</script>

 
 

Carriage returns and newlines in labels

You can put carriage returns in your labels by using the string \r\n. This means your labels will span multiple lines. Like so:

myBar.Set('chart.labels', 'John\r\n(Winner!)', ...)

 
 

Why is the Traditional Radar chart so called?

Historical reasons. There used to be two Radar charts in RGraph - the TRadar and an older one called the Pseudo radar chart. The Pseudo Radar chart was converted into the Rose chart. Renaming the TRadar will only cause problems and there's no pressing reason to do so, so for the moment it remains the TRadar chart.


 
 

Character set issues

If you're seeing strange, unrecognised characters in your text labels or titles, you may need to specify the correct character set that the browser should use. In PHP you can do this with the header() function (which, as the name suggests, sends a HTTP header):

<?php
    header("Content-Type: text/html; charset=ISO-8859-1");
?>

If you use Apache, you could use the header directive, though this may be overridden by other directives, eg AddDefaultCharset.


 
 

How to identify an RGraph object

Because identity can sometimes be a tricky affair, there are a few RGraph properties that you can use to check whether an object is an RGraph object:


 
 

Static Y axis

A static Y axis is useful if you have a wide chart but limited space. Whilst not part of the RGraph libraries itself, it can be achieved with a little HTML, like the graph shown. The HTML and the script to achieve this is documented in the source of this page. It involves placing an extra canvas above the graph with the Y axis drawn on it. This canvas doesn't move when the main canvas scrolls left and right.

Note: Because Firefox doesn't support the event.offsetX and event.offsetY properties and they have to be simulated, scrolling in conjunction with tooltips in this case and this browser doesn't work.

<div style="position: relative; float: right; margin-right: 10px; margin-top: 10px">
    <!-- The width here is set further down the page in script -->
    <canvas id="axes" width="0" height="200" style="position: absolute; top: 0; left: 0; z-index: 100"></canvas>
    <div style="width: 600px; overflow: auto">
        <canvas id="cvs" width="1000" height="200"></canvas>
    </div>
</div>

<script>
    window.onload = function ()
    {
        /**
        * This is the script that draws the graph
        */
        line = new RGraph.Line('cvs', [3,15,22,26,28,24,22,25,23,24,26,23,24,25,27,28,29,26,23,22,24,21,24,25]);
        line.Set('chart.noaxes', true); // We draw the Y axis ourselves
        line.Set('chart.gutter', 27);
        line.Set('chart.hmargin', 5);
        line.Set('chart.linewidth', 3);
        line.Set('chart.shadow', true);
        line.Set('chart.shadow.offsetx', 0);
        line.Set('chart.shadow.offsety', 0);
        line.Set('chart.shadow.blur', 15);
        line.Set('chart.shadow.color', 'red');
        line.Set('chart.text.angle', 15);
        line.Set('chart.tooltips', [
                                    'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December',
                                    'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'
                                   ]);
        line.Set('chart.labels', [
                                  '','Feb 09', 'Mar 09','Apr 09','May 09','Jun 09','Jul 09','Aug 09','Sep 09','Oct 09','Nov 09', 'Dec 09',
                                  'Jan 10', 'Feb 10', 'Mar 10','Apr 10','May 10','Jun 10','Jul 10','Aug 10','Sep 10','Oct 10','Nov 10', 'Dec 10'
                                 ]);
        line.Draw();



        /**
        * And this is the script that draws the left axis, on the other canvas (that doesn't move)
        */
        ca = document.getElementById("axes")
        co = ca.getContext('2d');


        /**
        * This sets the smaller canvas to cover the whole of the graphs left gutter
        */
        ca.width = line.Get('chart.gutter') + 1;


        RGraph.Clear(ca, 'white');


        /**
        * This draws the static axis
        */
        co.beginPath();
            co.moveTo(line.Get('chart.gutter'), line.Get('chart.gutter'));
            co.lineTo(line.Get('chart.gutter'), line.canvas.height - line.Get('chart.gutter'));

            // Draw the tickmarks on the axis
            var numTicks = 10;
            for (var i=0; i<=numTicks; ++i) {
                co.moveTo(line.Get('chart.gutter'), line.Get('chart.gutter') + (((ca.height - (2 * line.Get('chart.gutter'))) / numTicks) * i));
                co.lineTo(line.Get('chart.gutter') - 3, line.Get('chart.gutter') + (((ca.height - (2 * line.Get('chart.gutter'))) / numTicks) * i));
            }

        co.stroke();



        /**
        * This draws the labels for the static axis
        */
        co.beginPath();
            var color = 'black';
            var size = 10;

            for (var i=0; i<5; ++i) {
                co.fillStyle = color;
                co.textAlign = 'right';
                co.textBaseline = 'middle';
                var h = line.canvas.height - (2 * line.Get('chart.gutter'));

                RGraph.Text(co, 'Verdana', size, line.Get('chart.gutter') - 4, line.Get('chart.gutter') + (h * (i/5)), line.max - (line.max * (i/5)));
            }
        co.fill();
    }
</script>



 
 

Reducing white space

If the labels that you have require a large gutter you can reduce the amount of wasted space by using the standard 2D context method translate(). This effectively moves the coordinate system so that (0,0) is no longer in the top left corner, but whereever you put it. For example if you translate by (15,-15), the origin will then be 15 pixels right and 15 pixels up compared to where it was.

Because the coordinate system is being changed things that rely on coordinates, eg tooltips, will be affected. For this reason there is the property chart.tooltips.coords.adjust which you can use to tell RGraph that you've translated and the tooltip coordinates will be adjusted appropriately.

// This moves the graph to the right by 15px, and up by 15px. Do this before the call to .Draw()
myObject.context.translate(15,-15);
Note
With some graph types you can now specify the chart.width and chart.height properties to constrain the chart to a specific area of the canvas. This means you can have much more space for the labels.


 
 

In-graph labels

As well as an array of strings, like this:

obj.Set('chart.labels.ingraph', ['First label','Second label']);

The string can also be an array, consisting of color and placement information, like this:

obj.Set('chart.labels.ingraph', ['First label',['Second label', 'red', 'yellow', -1, 50] ]);

You can read more information about this here.


 
 

Shorthand for in-graph labels

Instead of providing a full array of null elements for in-graph labels which may get a little unwieldy, you can instead specify an integer that specifies how many elements to skip. Like this:

line.Set('chart.labels.ingraph', [6, 'July', 3, 'November']);



 
 

DOM2 Event handlers

All the graphs have now (1st October 2010) been converted to DOM2 for tooltips event registration. This allows them to be far more co-operative if you're using events. Tooltips will not be compatible with MSIE8 - the graphs will still be drawn, albeit without tooltips.



 
 

Gutter suggestion function

RGraph now contains a function (RGraph.getGutterSuggest()) that will provide a simple suggestion for the gutter setting. This function is based on the left gutter and labels and should be considered an approximate value.

You may also be interested in the chart.width and chart.height properties. These are a part of a limited set of graph types, and allow you to constrain the chart to a specific width/height.



 
 

Data types

If your data values aren't the correct type - ie numbers - it can cause problems. Pay particular attention to this when you're getting your data from data sources which may be classed as strings, such as JSON or AJAX requests.


 
 

Creating your own Graph type

If you wish to create your own graph type, there is a skeleton file here that you can use as a starting point. This file contains the bare bones of an RGraph object, such as the .Get() and .Set() methods, as well as examples of common properties.


 
 

World map

There is no function in RGraph to do mapping, either of the World or a smaller region. If this is what you want then you may be interested in this HTML5 canvas based mapping system: http://joncom.be/code/excanvas-world-map/


 
 

Known issues

There's a few known issues documented here