API documentation
Summary: Information about the API for the canvas based charts. You'll find a list of the RGraph functions as well information about how RGraph does things. If you're delving into the innards of RGraph and/or heavily customising your charts this page will be invaluable to you.
- Overview
- Canvas and context references
- Working with events
- Working with chart coordinates
- Working with chart data
- Updating your charts dynamically
- Setting properties
- References available on RGraph objects
- Scale information
- Adding text to your charts
- The
on()
function for events - RGraph functions
- The RGraph ObjectRegistry
Overview
Working with RGraph objects is purposefully easy, to make them straight forward to integrate into your own scripts if you want to. For any particular chart type there are a few files required - the common libraries and the chart specific library. Eg:
<script src="RGraph.common.core.js"></script> <script src="RGraph.bar.js"></script>
RGraph.common.core.js
is a function library that contains a large set of functions that
support the chart classes.
Some functions, and sets of functions, have their own files. For example,
the Google Sheets functionality resides in RGraph.common.sheets.js
,
so if you don't need this facility, you don't need this file.
Each of the chart libraries (RGraph.*.js
) contains that particular
charts class. If you'd like to see a "bare bones"
implementation, you can look at the basic examples which are included in the
archive.
Canvas and context references
Each chart object maintains references to the context
and canvas
as properties. So to get hold of them all you need to do is this:
<script> // 1/2 First draw the chart bar = new RGraph.Bar({ id: 'cvs', data: [1,5,8,4,6,3,1,5,7,8,4,6], options: { xaxisLabels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] } }).draw() // 2/2 Now get hold of the references context = bar.context; // Get hold of a reference to the context canvas = bar.canvas; // Get hold of a reference to the canvas </script>
Paths in the RGraph libraries
For speed and convenience - RGraph uses a custom path function in order to facilitate path drawing.
If you look through the RGraph source code you might see the RGraph.path()
function in use or calls to this.path()
.
This function makes the canvas path syntax, which is quite verbose,
much less so. As an example:
RGraph.path({ object: this, path: 'b r % % % % s % f %', args: [5, 5, 100, 100, 'black', 'red'] }); this.path( 'b r % % % % s % f %', 5,5,100,100, 'black','red' );
This is a shorter and clearer way of doing a beginPath()
,
rect()
(at x=5,y=5, 100 wide and 100 high) stroking it in black and finally
filling it in red.
For comparison here is the equivalent code that doesn't use the
path()
function:
this.context.beginPath(); this.context.rect(5, 5,100,100); this.context.strokeStyle = 'black'; this.context.fillStyle = 'red'; this.context.stroke(); this.context.fill();
If you're interested in an RGraph.path()
function that works with any canvas
(ie your own) then take a look at
the SVG-like path function.
This is a function that is added to the 2D context
(when you include the code in your page) and makes creating and using canvas paths far
nicer. It looks like this:
context.path('b r 0 0 100 100 f red');
That represents the following code:
context.fillStyle = 'red' context.beginPath(); context.rect(0,0,100,100); context.fill();
The RGraph.path()
function is part of the
RGraph.common.core.js
file and inside the RGraph classes it can be
referenced like this:
RGraph.path({ object: this, path: 'b r % % % % f %', args: [x, y, width, height, 'red'] });Or this:
this.path( 'b r % % % % f %', x, y, width, height, 'red' );
Update (version 5.2)
The syntax for calling this function was extended so that you can call
it from either inside or outside of your chart object in these ways:
// The RGraph.path() function is added as a member function to each chart object
bar.path({
path: 'b r % % % % f red',
args: [x, y, width, height]
});
// A less verbose way of calling the function - similar to the sprintf()
function
bar.path('b r % % % % f red', x, y, width, height);
bar.path('b r % % % % f red', x, y, width, height);
Working with events
When working with events, you may come across the situation where
you have a reference to the canvas
, but
also need to access the chart object. For this reason the
constructor of each RGraph chart object adds a reference to itself to the
canvas and you can access it like this:
<script>
document.getElementById("myCanvas").onclick = function (e)
{
var canvas = e.target;
// The RGraph object constructors add __object__ to the canvas.
var bar = canvas.__object__;
}
</script>
If you have multiple objects on your canvas (eg a combined Line
and Bar
chart) the __object__
reference will be a reference to the last
object
that you added to the canvas. So in order to get other objects
you'll
need to use the ObjectRegistry.
Working with chart coordinates
For many chart types, the coordinates of elements (eg bars, lines
etc) are to
be found in the variable obj.coords
.
This is usually a multi-dimensional array consisting of the
coordinates of those shapes or points. As an example the bar
chart maintains the X, Y, width and height of each bar (or sections
of bars in a stacked bar chart). The coordinates array is
usually a flat array, even when you have multiple sets of data.
The obj.coords2
array is similar but
indexed slightly differently. Eg In a grouped Bar chart the
obj.coords2[0]
array contains
all of the coordinates from the first group of bars - ie for a
group of three bars it will contain:
obj.coords2[0][0]
obj.coords2[0][1]
obj.coords2[0][2]
By using the RGraph.getMouseXY()
function and this array you can determine if a bar was clicked on, or if the mouse is near a
line point etc.
var coords = obj.coords;
Working with chart data
Another variable you may need is the data
variable. For most chart types, this is where the data is stored. It is usually
untouched, so it is as you supplied to the chart objects constructor. A notable exception to this is filled line charts.
Here the original data is stored in the variable obj.original_data
. The data supplied is modified to produce the stacking
effect. If you need to modify a filled line charts data you will need to change this variable instead.
Not all chart types use the data
variable. For some the name
is different so that it makes a little more sense. The
chart types and their associated data variables are listed below1.
Chart type | Data variable(s) |
---|---|
Bar | obj.data |
Bi-polar | obj.left , obj.right |
Donut | This is now a variant of the Pie chart |
Fuel | obj.min , obj.max , obj.value |
Funnel | obj.data |
Gantt | See the documentation |
Gauge | obj.min , obj.max , obj.value |
Horizontal Bar | obj.data |
Horizontal Progress bar | obj.min , obj.max , obj.value |
Line | obj.original_data 3 |
Meter | obj.min , obj.max , obj.value |
Odometer | obj.min , obj.max , obj.value |
Pie | obj.data |
Radar | obj.original_data |
Rose | obj.data |
Radial Scatter chart | obj.data |
Semi-circular Progress | obj.min , obj.max , obj.value |
Scatter | obj.data 2 |
Thermometer | obj.min , obj.max , obj.value |
Vertical Progress bar | obj.min , obj.max , obj.value |
Waterfall chart | obj.data |
- In the table, obj refers to your chart object.
- For the Scatter chart, each data point is an array of X/Y coordinates, the color and the tooltip for that point.
-
The Line chart
obj.original_data
is an aggregation of all the datasets given to the Line chart, so the first dataset is held inobj.original_data[0]
, the second inobj.original_data[1]
etc.
Updating your charts dynamically
Note:
It is important that you're careful with types when making AJAX requests. Since the response is initially a string,
and your AJAX function/library may not do conversions for you, you may need to convert these strings to numbers. To
do this you can use the Number()
parseInt()
or parseFloat()
functions. For example:
<script> num = Number('23'); num = parseInt('43'); dec = parseFloat('43.5'); </script>
RGraph has AJAX helper functions that minimise type conversion hassles. You can read more about these functions in the AJAX HOWTO guide.
RGraph.AJAX.getNumber(url, callback)
RGraph.AJAX.getString(url, callback)
RGraph.AJAX.getCSV(url, callback[, separator])
RGraph.AJAX.getJSON(url, callback)
RGraph.AJAX.post(url, data, callback)
Note: You could also use jQuery for AJAX queries:
<script>
$.get('/getData.html', function (data)
{
// Use the RGraph function $p() to show the returned data
$p(data);
});
</script>
A common request is to be able to update charts dynamically. This is quite straight-forward and consists of three steps:
- Get your new data from the server (with an AJAX request for example).
- Set the data on your chart object. See the above table for the appropriate property to use.
-
Call the
draw()
method again (you might need to use theRGraph.redraw()
function to fully redraw the canvas if you have multiple charts)
If you don't need to get data from your server (ie it's all client-side) then you can skip the first step. Also, it may be sufficient to simply recreate the entire object from scratch. This means that you won't have to update any RGraph internal properties - just recreate the chart object and configuration. Note though that if you update the chart frequently (ie multiple times per second) then performance may be slightly degraded.
Setting properties
To set RGraph properties you can use the JSON style configuration (which is the default now) or you can use each objects setter directly (there's also a corresponding getter).
obj.set({ marginLeft: 35, marginRight: 35, marginTop: 35, marginBottom: 35 }); obj.get('marginLeft'); obj.get('marginRight'); obj.get('marginTop'); obj.get('marginBottom');
References that are available on RGraph objects
RGraph stores various references to objects on the canvas
(typically) to make getting hold of them easier. There's also a
Registry
object in
which references and settings are stored. Typically the objects
are named with the format __xxx__
or with an obvious
prefix (such as the word rgraph
), and you can inspect the
objects by using a console (eg the inspector that's part of Google
Chrome - press CTRL+SHIFT+J
when viewing the webpage). Some examples are:
__object__
on the canvas - a reference to the chart object-
RGraph.Registry.get('tooltip')
- a reference to the currently visible tooltip (if any). This in turn has the following available:__text__
- Since settinginnerHTML
can cause changes in HTML, this is the original tooltip text.__index__
- This is the numerical index corresponding to the tooltips array that you set.__dataset__
- Used in some charts and corresponding to the dataset.__canvas__
- A reference to the original canvas that triggered the tooltip.
-
RGraph.Registry.get('mousedown')
- Used in annotating, and stipulates whether the mouse button is currently pressed. -
RGraph.Registry.get('contextmenu')
- The currently shown context menu, if any. This in turn has the following properties:__canvas__
- The original canvas object.
Scale information
For the Bar, Bipolar, Horizontal Bar, Line, Scatter and
Waterfall charts the scale that is used is stored in the
scale2
class variable. Eg:
<script> bar = new RGraph.Bar({ id: 'cvs', data: [56,43,52,54,51,38,46,42,52] }).draw(); scale = bar.scale2; </script>
Adding text to your charts
If you want to add arbitrary text to your chart(s) you can
either use
the RGraph.Drawing.Text
drawing API object or use
the RGraph text
function directly. The drawing API object has advantages in
that it supports adding tooltips and/or click
/mousemove
events
to the text and is automatically redrawn for you.
So if you do use tooltips or other interactive features then you don't have
to worry about using the draw
event.
The on() function for events
The on()
function can be used to set events
(both custom and the click
/mousemove
events) on your canvas
without breaking
method chaining. For example:
bar = new RGraph.Bar({
id: 'cvs',
data: [4,8,6,4,3,5,4],
options: {
marginLeft: 35,
marginBottom: 35,
xaxisLabels: ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
}
}).on('draw', function (obj)
{
alert('Chart has been drawn!');
}).draw()
RGraph functions
This is a list of some of the functions available to you in the RGraph common libraries. Arguments in square brackets are optional.
<script src="RGraph.common.core.js"></script>
<script>
// Returns 9
var arr = [3,2,5,4,9,7,8];
var max = RGraph.arrayMax(arr);
</script>
Arrays
(number) RGraph.arrayMin(array)
Returns the minimum value in the array.
File: RGraph.common.core.js(number) RGraph.arrayMax(array)
Returns the maximum value in the array.
File: RGraph.common.core.js(number) RGraph.arraySum(array)
Returns the sum of all values in the array. You can also pass a single integer, in which case it is simply returned as-is.
File: RGraph.common.core.js(array) RGraph.arrayClone(array)
Creates a copy/clone of the given array. Only numerically indexed arrays are supported.
File: RGraph.common.core.js(array) RGraph.arrayReverse(array)
Returns a reversal of the given array.
File: RGraph.common.core.js(boolean) RGraph.isArray(obj)
Returns true or false as to whether the given object is an array or not.
File: RGraph.common.core.js(array) RGraph.arrayPad(array, length[, value])
Pads the given array to the specified length (if the length is less, if not the array is returned as is). The third, optional, argument is the value which is used as the pad value. If not specified,null
is used.
File: RGraph.common.core.js(array) RGraph.arrayShift(array)
Shifts an element off of the start of the given array and returns the new array.
File: RGraph.common.core.js-
(array) RGraph.arrayLinearize(arr1, arr2, arr3, ...)
This function takes any number of arrays as arguments and concatenates them all into on big array. Similar to the standard JavaScriptconcat()
function. -
(array) RGraph.sequentialIndexToGrouped(index, data)
This function can be used to convert sequential indexes (such as tooltips or the .coords array) to into grouped indexes. For example you may have an index of 5, but need to convert it into one that is usable with the data:[[4,6,5],[4,3,2],[1,5,2]]
(eg a stacked/grouped bar chart). This function will do that for you. It returns a two element array containing the group index and the index into that group. So your index of five becomes:[1, 2]
File: RGraph.common.core.js
-
(array) RGraph.arrayInvert(array)
This function can be used to invert values in an array from true to non-true and vice-versa. So an array containing two true values and six non-true values becomes an array of two non-true values and six true values.
File: RGraph.common.core.js
-
(array) RGraph.arrayRandom(num, min, max)
This function provides an easy way to generate an array filled withnum
random values betweenmin
andmax
.
File: RGraph.common.core.js
Strings
(string) RGraph.rtrim(string)
Strips the right hand white space from the string that you pass it.
File: RGraph.common.core.js-
(string) RGraph.numberFormat({object: obj, number: number [, unitspre: prepend[, unitspost: append[, point: decimal_point[, thousand: thousand_separator]]]]})
This formats the given number (which can be either an integer or a float. The prepend and append options are strings which are added to the string (eg 5%).
Note: As of the January 2019 release this functions argument list has been changed to accept a single object instead of multiple separate arguments. So you might call this function like so:RGraph.numberFormat({ object: obj, number: num, unitspre: '$', unitspost: 'c', point: '.', thousand: ',' });
File: RGraph.common.core.js
Numbers
-
(mixed) RGraph.abs(number)
This function operates similarly to theMath.abs()
function except that it also handles arrays and objects (recursively). It applies theMath.abs()
function to each element.
File: RGraph.common.core.js
(number) RGraph.random(min, max)
Returns a random number between the minimum and maximum that you give. To get an array filled with random values you can use theRGraph.arrayRandom()
function detailed above.
File: RGraph.common.core.js(string) RGraph.numberFormat()
See above.
File: RGraph.common.core.js(number) RGraph.log(number, base)
This function returns the logarithm value for the given number using the given base.
File: RGraph.common.core.js
Miscellaneous
-
(string) RGraph.clearEventListeners(id)
This is the function to use if you want to clear the canvas or window official DOM2 event listeners (eg that facilitate things like tooltips). The id argument that you pass it should be either theID
of the canvas (the same as what you pass todocument.getElementById()
), or justwindow
if you want to clear the window event listeners. Keep in mind though that if you clear the window event listeners it will affect all canvas tags on the page.
File: RGraph.common.core.js -
(string) RGraph.createUID()
This function is used to create a Unique ID for each object (which is done in their constructors). This UID can then be used to identify a single object. There is an associatedObjectRegistry
method:RGraph.ObjectRegistry.getObjectByUID()
which can then be used to retrieve an object with the UID.
File: RGraph.common.core.js -
(object) RGraph.Effects.wrap(canvas)
This function is used by some animation functions to stop the page layout changing when the canvas is removed from the document. It removes the canvas from the document, replaces it with a DIV and then adds the canvas as a child node of the DIV. The canvas is placed in the center of the DIV.
File: RGraph.common.effects.js (null) RGraph.pr(mixed)
Emulates the PHP functionprint_r()
by recursively printing the structure of whatever you pass to it. It handles numbers, strings, arrays, booleans, functions and objects.
File: RGraph.common.core.js(null) $p(mixed)
An alias of the above albeit shorter to type.
File: RGraph.common.core.js-
(null) $cl(mixed)
A shortcut for the debug functionconsole.log()
.
File: RGraph.common.core.js -
(null) $a(mixed)
A shortcut for the standardalert()
function.
File: RGraph.common.core.js
-
(null) RGraph.clear(canvas[, color])
Clears the canvas by drawing a clear (or the optional color you give) rectangle over it. If you don't specify a color and your chart (or if you have multiple charts on the canvas - the last chart that you created) has theclearto
option specified (egobj.set('clearto', 'white')
) then this function will use that color when clearing the canvas - essentially a default clear color.
File: RGraph.common.core.js -
(null) RGraph.clearAnnotations(canvas)
This function clears the annotation data associated with the given canvas (but DOES NOT redraw the chart). If you want to clear the visible annotations too, you will need to redraw the canvas. You could do this using the following code:
function clearAndRedraw (obj) { RGraph.clearAnnotations(obj.canvas); RGraph.clear(obj.canvas); obj.draw(); }
File: RGraph.common.annotatate.js (null) RGraph.replayAnnotations(object)
This function redraws any annotations which have previously been drawn on the canvas. You would use this function when annotations are turned off and you want previous annotations to be displayed.
File: RGraph.common.annotate.js(array) RGraph.getMouseXY(event)
When passed your event object, it returns the X and Y coordinates (in relation to the canvas) of the mouse pointer. (0,0) is in the top left corner, with the X value increasing going right and the Y value increasing going down.
File: RGraph.common.dynamic.js(array) RGraph.getCanvasXY(canvas)
Similar to the above function but returns the X/Y coordinates of the canvas in relation to the page.
File: RGraph.common.core.js-
(array) RGraph.getScale(args)
Given the maximum value this will return an appropriate scale. The argument is an object which can contain two properties -object
andoptions
(an object containing configuration properties). Theoptions
object can contain these options:
scale.max
The maximum valuescale.min
The minimum valuescale.labels.count
Number of labels to generatescale.unit.pre
These units are placed before the numberscale.unit.post
These units are placed after the number-
scale.strict
Giving a max value of (for example) 96 will generate a scale that goes to 100 - though if you specify thestrict
option you will get a scale that goes to 96. scale.decimals
The number of decimals to showscale.point
The character used to indicate a decimal point (default is . )scale.thousand
The character used to indicate a thousand separator-
scale.round
Whether to round the scale up. eg A scale might be generated with a maximum value of 600, whereas if you specify this option the scale would be rounded to 1000.
(mixed) RGraph.Registry.get(name)
In conjunction with the next function, this is an implementation of the Registry pattern which can be used for storing settings.
File: RGraph.common.core.js(mixed) RGraph.Registry.set(name, value)
In conjunction with the previous function, this is an implementation of the Registry pattern which can be used for storing settings.
File: RGraph.common.core.js-
(null) RGraph.register(object)
This function is used in conjunction with the next to register a canvas for redrawing. Canvases are redrawn (for example) when tooltips or crosshairs are being used. See the section below for details on the RGraphObjectRegistry
which is used to facilitate multiple charts on one canvas.
File: RGraph.common.core.js
-
(null) RGraph.redraw([color])
This function is used in conjunction with the previous to redraw a canvas. Canvases are redrawn (for example) when tooltips or crosshairs are being used.
Note: All canvases that are registered are redrawn. The optional argument is the color to use when clearing canvases.
File: RGraph.common.core.js
-
(null) RGraph.redrawCanvas(canvas)
Similar to theredraw()
function but only redraws the specified canvas tag (instead of all (RGraph) canvas tags on the page).
File: RGraph.common.core.js
-
(null) RGraph.setShadow(object, color, offetX, offsetY, blur)
This function is a shortcut function used to set the four shadow properties. The arguments are: your chart object, the shadow color, the X offset, the Y offset, the shadow blur.
File: RGraph.common.core.js
(null) RGraph.setShadow(opt)
An alternative way of calling the function - you can give it an object which has two properties:object
prefix
RGraph.setShadow({ object: obj, prefix: 'shadow' });
The prefix should be the first part of the property names - egshadow
will set theshadowColor
,shadowOffsetx
,shadowOffsety
andshadowBlur
properties, (you might recognise them better asshadowColor
,shadowOffsetx
,shadowOffsety
,shadowBlur
).
File: RGraph.common.core.js(null) RGraph.setShadow(object)
Like theRGrapph.noShadow()
function you can give this function a solitary object and the shadow will be turned off.
File: RGraph.common.core.js(null) RGraph.noShadow(object)
This function is a shortcut function used to "turn off" the shadow. The argument is your chart object.
File: RGraph.common.core.js-
(number) RGraph.async(mixed[, delay])
This is a simple function but has significant implications on your pages performance. You can pass this either a function pointer, or a string containing the code to run and it will run the code asynchronously (ie in parallel to the page loading). In doing so it can mean that your page is displayed faster, as the chart is created separate to the page loading. As such, the placement of your canvas tag becomes more important. What you can do is define the canvas tag and then the code to produce the chart immediately after it. There's an example of it here. The optional delay argument is measured in milliseconds (1 second = 1000 milliseconds) and defaults to 1. What you can do is specify something like 1000 to make the effect more pronounced to ensure it's working as expected.
File: RGraph.common.core.js
-
(null) RGraph.roundedRect(context, x, y, width, height[, radius[, roundtl[, roundtr[, roundbl[, roundbr]]]]])
This draws a rectangle with rounded corners. Similar to the built in rectangle functions and you can control individual corners. The radius controls the severity of the corner curvature and defaults to 3. By default all the corners are rounded. Note that the rectangle is not filled or stroked. So to create a rounded rectangle you'll need to do something like this:
context.beginPath(); context.strokeStyle = 'black'; context.fillStyle = 'red'; RGraph.roundedRect({ context: context, x: 5, y: 5, width: 100, height: 100, radius: 25, roundbl: false, roundbr: false }); context.stroke(); context.fill();
File: RGraph.common.core.js
-
(null) RGraph.reset(canvas)
This function resets the canvas. At first this function may appear similar to the RGraph.clear() function, however this function will reset any translate that has been performed, so can stop them accumulating. It also clears theObjectRegistry
for the specific canvas - so if you use one canvas to show multiple charts you may need to use this method in-between the charts.
File: RGraph.common.core.js
-
(object) RGraph.linearGradient({object: obj, x1: x1, y1: y1, x2: x2, y2: y2, colors: [color1, color2[, color3, ...]]})
This is a shortcut function for creating a linear gradient. You specify the X/Y coordinates and the colors and it returns the gradient. You can specify more than two colors if you wish.An example of this functions use is:grad = RGraph.linearGradient({ object: obj, x1: 0, y1: 0, x2: 0, y2: 250, colors: ['red', 'black'] });
File: RGraph.common.core.js
-
(object) RGraph.radialGradient({object: obj, x1: x1, y1: y1, r1: r1, x2: x2, y2: y2, r2: r2, colors: [color1, color2[, color3, ...]]})
This is a shortcut function for creating a radial gradient. You specify the X/Y coordinates, the radius and the colors and it returns the gradient. You can specify more than two colors if you wish.grad = RGraph.radialGradient({ object: obj, x1: 250, y1: 250, r1: 0, x2: 250, y2: 250, r2: 250, colors: ['red', 'black'] });
File: RGraph.common.core.js
-
(null) RGraph.path(obj, path)
This is an update of theRGraph.path()
function which supports more operations and has even more concise syntax. You don't need to choose between the two path functions - just useRGraph.path()
. Inside the RGraph source code you'll see this being referenced asthis.path()
. You can read all about this function and see the available path options in this blog article.
-
(number) RGraph.parseDate(string)
The parseDate function is similar to theDate.parse()
function in that it takes a date string and returns a number which is the number of milliseconds since January 1st 1970. It goes a little further then theDate.parse()
function by allowing extra formats of date/time:- 2013-11-22 12:12:12
- 2013/11/22 12:12:12
- 2013-11-22
- 12:09:44 (todays date is used)
- June 21st 1984
- Other formats are supported - so just try yours and see!
Date.parse()
natively supports are also supported.
File: RGraph.common.core.jsNote: To parse dates and/or times you can also use the
Moment.js
library which is now included in the RGraph download. The date/time HOWTO document has a little bit more of information.
Custom RGraph event related functions
(null) RGraph.fireCustomEvent(object, event)
This fires a custom event. The object is your chart object, and the name is a string specifying the name of the event.
File: RGraph.common.core.js(number) RGraph.addCustomEventListener(object, event, callback)
This attaches a function to the specified event. The object argument is your chart object, the event argument should be the name of the event, egtooltip
, and the function argument is your function which handles the event. The return value is an ID which can be used with theRGraph.removeCustomEventListener()
function.
File: RGraph.common.core.js(null) RGraph.removeCustomEventListener(object, id)
This removes the custom event listener that corresponds to the given ID. The arguments are the chart object and the ID of the event handler to remove (as returned byRGraph.addCustomEventListener()
).
File: RGraph.common.core.js(null) RGraph.removeAllCustomEventListeners([id])
To easily remove all custom event listeners you can use this function. It also can optionally take one argument - a canvas ID - to limit the clearing to.
File: RGraph.common.core.js
For clearing the standard event listeners that RGraph installs - see the miscellaneous section
Trigonometry functions
-
(number) RGraph.toRadians(degrees)
Converts and returns the given number of degrees to radians. Roughly, 1 radian = 57.3 degrees.
File: RGraph.common.core.js
-
(number) RGraph.toDegrees(radians)
This a function that does the reverse of the above function and converts radians to degrees.
File: RGraph.common.core.js
-
(number) RGraph.getAngleByXY(cx, cy, x, y)
Given two pairs of coordinates this function will return the appropriate angle that the line is at.
File: RGraph.common.core.js
-
(number) RGraph.getHypLength(x1, y1, x2, y2)
Using Pythagoras this function will return the length of the line between the two given points.
File: RGraph.common.core.js
-
(number) RGraph.getRadiusEndPoint(x, y, angle, radius)
Using trigonometry functions (sin/cos) this function gives you the coordinates of the end point of a radial line. You pass it the center X/Y, the angle and the radius.
File: RGraph.common.core.js
-
(null) RGraph.rotateCanvas(canvas, x, y, angle)
This function can be used BEFORE you draw your chart to rotate the canvas. The canvas is rotated about the X/Y coordinates that you give by the angle (which is measured in RADIANS). Angles can be negative.
File: RGraph.common.core.js
Other
These are functions which are less generic, and used to build the charts. You may still wish to use them however.
-
(null) RGraph.text(options)
This function is a rewrite of the original text function. It's faster than its predecessor and its return value is an object that contains the coordinates of the text (unless the text is angled). These coordinates are also stored on the given object in theobj.coordsText
array. By using these coordinates you can use them in conjunction with the Rect drawing object and create clickable text. An easier alternative to that though may be to simply use the Drawing API Text object. The various properties that you can use with this function are:
object
- An RGraph object used to get the context fromcolor
- The color used to draw the textfont
- The font used to draw the textsize
- The size used to draw the text (in points)x
- The X position of the texty
- The Y position of the texttext
- The text to displaybounding
- Whether to draw a bounding box around the textboundingStroke
- The stroke color of the bounding boxboundingFill
- The fill color of the bounding boxboundingShadow
- Whether the bounding box has a shadowboundingShadowColor
- The color of the shadowboundingShadowBlur
- The severity of the shadow blurboundingShadowOffsetx
- The X offset of the shadowboundingShadowOffsety
- The Y offset of the shadowboundingLinewidth
- The linewidth used to draw the bounding boxbold
- Whether the text is bold or notmarker
- Whether to show a positioning markerhalign
- The horizontal alignment of the textvalign
- The vertical alignment of the text-
tag
- This can be used to supply a helpful identifier that can later be used to search for the text in theobj.coordsText
array. accessible
- Whether to use accessible DOM text or not. The default is to use accessible text.
File: RGraph.common.core.js
RGraph.text({ object: obj, font: 'Arial', size: 10, bold: false, text: 'Some text', x: 100, y: 100, valign: 'bottom', // bottom/center/top halign: 'left', // left/center/right bounding: false, boundingFill: 'red', // Don't forget the quotes around the key boundingStroke: 'black', // Don't forget the quotes around the key marker: false, tag: 'myTag' });
-
(array) RGraph.text.find(options)
If you use accessible text then you can use this function to retrieve the actual DOM nodes (which are <span> tags). Theoptions
argument should be an object which contains the details of what you want to search for. The arguments are ORed, so if you search specify two criteria and two different nodes match - both nodes will be returned. The object can contain the following:
-
id
- The ID of the canvas tag. If you prefer you can give the object argument instead. -
object
- This can be given instead of theid
option and is used to get the canvas ID.
-
-
tag
- This can be a string or a regular expression that is matched against the tag of the text. -
text
- This can be a string or a regular expression that is matched against the text itself. -
callback
- This can be a function that is called when the search has completed and any matching nodes have been found. The function is given an object as its sole argument. This object has two properties -nodes
which is an array of any matching nodes that have been found andobject
which is the chart object.
// Using a string of text as the tag
var nodes = RGraph.text.find({
id: 'cvs',
tag: 'labels'
});
// Using a regex as the tag
var nodes = RGraph.text.find({
object: myBar,
tag: /^lab/
});
// Using a string as the text option
var nodes = RGraph.text.find({
id: 'cvs',
text: '10km'
});
// Using a regex as the text option
var nodes = RGraph.text.find({
id: 'cvs',
text: /^10/
});
// Using the callback option var nodes = RGraph.text.find({ id: 'cvs', text: /^10/ callback: function (args) { var obj = args.object, nodes = args.nodes; // Do something here } });Remember that this function only works if you use accessible text (which is the default now).
File: RGraph.common.core.js
(null) RGraph.drawTitle(object, text, margin[, centerx[, size]])
This function draws the title. The centerx argument is the center point to use. If not given the center of the canvas is used.
File: RGraph.common.core.js
(null) RGraph.tooltip(object, text, x, y, index, event)
This function shows a tooltip. The index value corresponds to the tooltip array that you give. The event argument is the event object.
File: RGraph.common.tooltips.js
(null) RGraph.hideTooltip([canvas])
This function hides the tooltip. The optional argument can be a canvas object (the same as what you get back from
document.getElementById()
) and if given the tooltip is only cleared if it
originates from that canvas.
File: RGraph.common.tooltips.js
(null) RGraph.drawKey(object, key, colors)
This function draws the key. The first argument is the chart object, the second is an array of key information and the last is an array of the colors to use.
File: RGraph.common.key.js
(null) RGraph.drawBars(object)
This draws the horizontal background bars. The argument is the chart object.
File: RGraph.common.core.js
(null) RGraph.drawInGraphLabels(object)
This draws the in-graph labels. The argument is the chart object.
File: RGraph.common.core.js
(null) RGraph.drawCrosshairs(object)
This function draws the crosshairs. The argument is the chart object.
File: RGraph.common.core.js
(null) RGraph.hideContext()
This function clears the context menu. RGraph uses it to hide the context menu, but only AFTER your function/callback is run. You may wish to hide the context menu before your own function, in which case you can call this function.
File: RGraph.common.context.js
(null) RGraph.showPNG([canvas[, event]])
This function allows you to easily facilitate getting a PNG image representation of your chart. You can use it like this:
bar.set({
contextmenu: [
['Get PNG', RGraph.showPNG],
null,
['Cancel', function () {}]
]
});
Optionally, you can pass in the canvas as an argument which will be
used, meaning now you do not have to use a
context menu (there's an example here).
It was originally designed to be used with a context menu, hence it's
part of the RGraph.core.context.js file.File: RGraph.common.context.js
(null) RGraph.Background.draw(obj)
This function is used by the Bar, Gantt, Line and Scatter chart to draw the chart background (but not the axes). It is passed the chart object which it uses to get the properties it uses:
margin
variant
textSize
textFont
title
xaxisTitle
xaxisTitlePos
yaxisTitle
yaxisTitlePos
backgroundBarsColor1
backgroundBarsColor2
backgroundGrid
backgroundGridWidth
backgroundGridAlign
backgroundGridAlines
backgroundGridAlines
backgroundGridHlinesCount
backgroundGridVlinesCount
backgroundGridColor
backgroundGridBorder
Note that this function also calls RGraph.drawTitle()
in order to draw the title.
File: RGraph.common.core.js
(null) RGraph.drawBackgroundImage(obj)
This function draws the
backgroundimage
for the chart (the Line/Bar/Scatter charts). When you use background images there is
a very small delay between calling the canvas 2D drawImage()
API function and the image then loading. Because of this
when you call the drawImage()
function the image isn't actually loaded yet. Therefore when the image IS loaded, the RGraph
drawBackgoundImage()
function does a redraw()
so that the image is painted on to the canvas.File: RGraph.common.core.js
(null) RGraph.AJAX(url, callback)
This function can be used to make AJAX requests to your server (eg to fetch new data without refreshing the page). The response text is given to your callback function as an argument. You would use it like this:
<script>
RGraph.AJAX('/getdata.html', function (str)
{
// Handle the response and create the chart
});
</script>
File: RGraph.common.core.js(null) RGraph.AJAX.getString(url, callback)
This function can be used to make AJAX requests to your server (eg to fetch new data without refreshing the page). The response text is given to your callback function as an argument. This function is much the same as the above function though because of the name may aid you by being a visual prompt. You would use it like this:
<script>
RGraph.AJAX.getString('/getdata.html', function (str)
{
// Handle the response and create the chart
});
</script>
File: RGraph.common.core.js(null) RGraph.AJAX.getNumber(url, callback)
This function can be used to make AJAX requests to your server (eg to fetch new data without refreshing the page). The response text is given to your callback function as an argument but it's automatically converted to a number for you (using the JavaScript
parseFloat()
function). You would use it like this:
<script>
RGraph.AJAX.getNumber('/getdata.html', function (number)
{
// Handle the response and create the chart
});
</script>
File: RGraph.common.core.js(null) RGraph.AJAX.getJSON(url, callback)
This function can be used to make AJAX requests to your server (eg to fetch new data without refreshing the page). The response text is given to your callback function as a JavaScript object (your JSON string is parsed using
eval('(' + response + ')')
. You would use it like this:
<script>
RGraph.AJAX.getJSON('/getdata.html?json', function (json)
{
// Handle the response and create the chart
});
</script>
File: RGraph.common.core.js(null) RGraph.AJAX.getCSV(url, callback[, separator: separator])
This function can be used to make AJAX requests to your server (eg to fetch new data without refreshing the page). The response text is given to your callback function as a JavaScript array which is created from the first line of your CSV data). You would use it like this:
<script>
RGraph.AJAX.getCSV('/getdata.html', function (csv)
{
// Handle the response and create the chart
}, ',');
</script>
File: RGraph.common.core.js(null) RGraph.dashedLine(context, x1, y1, x2, y2[,size])
This function can be used to add dashed or dotted lines to your canvas. The arguments are the context , the start coordinates and the end coordinates. You can optionally specify a fifth argument which is used as the size of the dashes (the default is 5px).
File: RGraph.common.core.js
The RGraph ObjectRegistry
The RGraph ObjectRegistry
allows you to have
multiple charts on a single canvas - both having
dynamic features - such as the combined Bar and Line chart
shown here.
You can combine any of the chart types in RGraph, such as Meters, gauges, Progress bars etc. Because it's a common combination, there's a special class for combined Bar and Line chart which you use like this:
<script>
bar = new RGraph.Bar({
id: 'cvs',
data: [4,8,5,7,8,9],
options: {
xaxisLabels: ['Alex','Doug','Charles','Nick','Michelle','Ali'],
colors: ['red'],
tooltips: ['Alex','Doug','Charles','Nick','Michelle','Ali'],
textSize: 14,
marginInner: 20,
combinedEffect: 'wave',
yaxis: false,
backgroundGridVlines: false,
backgroundGridBorder: false
}
});
line = new RGraph.Line({
id: 'cvs',
data: [3,9,4,9,6,5],
options: {
textSize: 14,
colors: ['black'],
linewidth: 2,
tooltips: ['1984','1985','1986','1987','1988','1989'],
shadow: false,
spline: true,
combinedEffect: 'trace'
combinedEffectOptions: '{frames: 60}'
}
});
// Create the combination object - this draws the chart for us
combo = new RGraph.CombinedChart(bar, line).draw();
</script>
You can have as many chart types as you want with the CombinedChart class, though the Bar should be the first one that you add to it. Because it's a common combination the CombinedChart class changes the Line chart margins to match the Bar charts.
When you create an object it's added to the ObjectRegistry
automatically so that it can be redrawn as needed. Objects are
indexed by canvas ID and also by UID. This means that you can quickly get hold of all of the pertinent objects for a
given canvas, or one particular object if you need it. The following methods are available:
Note: You can also use these aliases:
RGraph.OR |
An alias to RGraph.ObjectRegistry (you can use this alias with all the ObjectRegistry functions) |
RGraph.OR.firstbyxy() |
An alias to RGraph.ObjectRegistry.getFirstObjectByXY() |
RGraph.OR.get() |
An alias to RGraph.ObjectRegistry.getObjectByUID() |
RGraph.OR.type() |
An alias to RGraph.ObjectRegistry.getObjectsByType() |
RGraph.OR.first() |
An alias to RGraph.ObjectRegistry.getFirstObjectByType() |
-
RGraph.ObjectRegistry.add(object)
This method adds an object to theObjectRegistry
. It's used predominantly by theRGraph.register()
function.
File: RGraph.common.core.js
-
RGraph.ObjectRegistry.remove(object)
This method removes an object from theObjectRegistry
. You may need to use this if you draw multiple charts on the same canvas otherwise ALL of the objects that you have created will be drawn when you redraw the canvas.
File: RGraph.common.core.js
-
RGraph.ObjectRegistry.clear([id])
This method clears theObjectRegistry
back to a state where nothing is registered. You can optionally give it either a canvas tag ID (a string) or the actual canvas tag itself (as returned bydocument.getElementById()
) and the clearing of theObjectRegistry
will be limited to that canvas.
File: RGraph.common.core.js
-
RGraph.ObjectRegistry.clearbyType(type)
This function is similar to theclear()
function but limits the clearing action to those objects of the specified type.
File: RGraph.common.core.js
-
RGraph.ObjectRegistry.iterate(function[, type(s)])
Theiterate()
function provides an easy way to go through all or some of the objects in theObjectRegistry
. The first argument should be a function which is called for every matching object in theObjectRegistry
. By default this function iterates through each object in theObjectRegistry
, but the second argument can be a comma separated list of one or more desired object types and the sole argument passed to the function is the object. Some examples of its usage:// Iterate through all of the objects in the
ObjectRegistry
RGraph.ObjectRegistry.iterate(function (obj) { alert('The objects UID is: ' + obj.uid); }); // Iterate through all of the bar chart objects in the ObjectRegistry RGraph.ObjectRegistry.iterate(function (obj) { alert('The objects UID is: ' + obj.uid); }, 'bar'); // Iterate through all of the bar,line and pie chart objects in the ObjectRegistry RGraph.ObjectRegistry.iterate(function (obj) { alert('The objects UID is: ' + obj.uid); }, 'bar,line,pie');
File: RGraph.common.core.js
-
RGraph.ObjectRegistry.list()
A debug style function that lists each object type that is held in theObjectRegistry
.
File: RGraph.common.core.js
-
RGraph.ObjectRegistry.getObjectsByCanvasID(id)
This method takes the ID of a canvas and returns all of the objects that are associated with it.
File: RGraph.common.core.js
-
RGraph.ObjectRegistry.getFirstObjectByXY(e)
This method takes an event object and returns the pertinent object. It only returns ONE object - unlike the function below so you may find it easier to use if, for example, you're creating a bank of Meters or Gauges.
File: RGraph.common.core.js
-
RGraph.ObjectRegistry.getObjectsByXY(e)
This method takes an event object and returns the pertinent objects that the mouse is positioned over, It returns an array of chart object because there may be multiple applicable objects (eg a Bar/Line combined chart.
File: RGraph.common.core.js
-
RGraph.ObjectRegistry.getObjectByUID(uid)
This method takes a UID (which can be retrieved withobj.uid
) and returns the pertinent object. Note that UIDs are unique to a single request only. So if you refresh the page they will change. They can be used, however, to distinguish between objects in a single request.
File: RGraph.common.core.js
-
RGraph.ObjectRegistry.getObjectsByType(type)
This method returns an array of objects which are of the given type. As of January 2013 its arguments list has changed so now it just takes the desired type of object (eg pie, line, bar etc).
File: RGraph.common.core.js
-
RGraph.ObjectRegistry.getFirstObjectByType(type)
As of January 2013 this objects argument list has changed - it now only accepts one argument - the type (eg pie, bar, line) and returns the first object that is in theObjectRegistry
that has that type.
File: RGraph.common.core.js
-
RGraph.ObjectRegistry.bringToFront(obj)
This method removes an object from theObjectRegistry
and pushes it on to the end - essentially moving the object to the top/front of the stacking order. File: RGraph.common.core.js
Note:
Since the ObjectRegistry
was introduced objects have to be
registered regardless of whether they use dynamic features
or not. As a result of this you may be experiencing objects
being redrawn when you don't want them to be. To
solve this you need to remove them from the ObjectRegistry
.
How to do this is documented
here.