Internal API documentation
- Overview
- Canvas and context references
- Paths in the RGraph libraries
- 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 straightforward 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 that 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 contextcanvas
= bar.canvas; // Get hold of a reference to thecanvas
</script>
Paths in the RGraph libraries
For speed and convenience - RGraph uses a custom path function 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 chart
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 flat, 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) |
---|---|
Activity | obj.min , obj.max , obj.value |
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 |
Horseshoe | obj.min , obj.max , obj.value |
Horizontal Progress | 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 | obj.data |
Semi-circular Progress | obj.min , obj.max , obj.value |
Scatter | obj.data 2 |
Segmented | obj.min , obj.max , obj.value |
Thermometer | obj.min , obj.max , obj.value |
Vertical Progress | obj.min , obj.max , obj.value |
Waterfall | 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 theLine chart
, so the first dataset is held inobj.original_data[0]
, the second inobj.original_data[1]
etc.
Updating your charts dynamically
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 javascript
Number
parseInt
or parseFloat
functions. For example: <script> num = Number('23'); num = parseInt('43'); dec = parseFloat('43.5'); </script>
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 thecanvas
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 thecanvas
- 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 inhtml
, 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 originalcanvas
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 originalcanvas
object.
Scale information
For the Bar chart
, Bipolar chart
,
Horizontal Bar chart
, Line chart
,
Scatter chart
and
Waterfall chart
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], options: { } }).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
- Type checking functions
- GET functions
- Clipping
- Arrays
- Strings
- Numbers
- Miscellaneous
- Custom RGraph event-related functions
- Trigonometry functions
- Other
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>
Type checking functions functions
(boolean) RGraph.isString(value)
Returnstrue
orfalse
depending on whether the supplied variable is a string or not.
File: RGraph.common.core.js(boolean) RGraph.isNumber(value)
Returnstrue
orfalse
depending on whether the supplied variable is a number or not.
File: RGraph.common.core.js(boolean) RGraph.isNumeric(value)
Returnstrue
orfalse
depending on whether the supplied variable is a numeric string or not (ie a string that looks like a number). Numeric types can include:496
12.34
-78
6e78
-6.59e-3
0xab
Infinity
-Infinity
0
-0
Newer types (egBinary
,BigInt
are not accommodated for)
File: RGraph.common.core.js(boolean) RGraph.isTextual(value)
Returnstrue
orfalse
depending on whether the supplied variable is either a string or a number.
File: RGraph.common.core.js(boolean) RGraph.isBoolean(value)
Returnstrue
orfalse
as to whether the given value is a boolean (true
orfalse
) or not.
File: RGraph.common.core.js(boolean) RGraph.isArray(value)
See below.
File: RGraph.common.core.js(boolean) RGraph.isObject(value)
Returnstrue
orfalse
depending on whether the given value is an object or not. Note that if you givenull
to this function you'll getfalse
even though technicallynull
is anobject
If you want to test fornull
values then you need to use theRGraph.isNull
or theRGraph.isNullish
functions.
File: RGraph.common.core.js(boolean) RGraph.isNull(value)
Returnstrue
orfalse
depending on whether the given value isnull
or not.
File: RGraph.common.core.js(boolean) RGraph.isNullish(value)
Returnstrue
orfalse
depending on whether the given value isnull
OR if the value isundefined
.
File: RGraph.common.core.js(boolean) RGraph.isFunction(value)
Returnstrue
orfalse
depending on whether the given value is a function or not.
File: RGraph.common.core.js(boolean) RGraph.isUndefined(value)
Returnstrue
orfalse
depending on whether the given value isundefined
or not.
File: RGraph.common.core.js
GET functions
(string) RGraph.GET.string(name)
Fetches a string query string parameter (the returned values type isString
).
File: RGraph.common.core.js(number) RGraph.GET.number(name)
Fetches a number query string parameter (the returned values type isNumber
).
File: RGraph.common.core.js(object) RGraph.GET.json(name)
Fetches ajson
query string parameter (the returned values type isObject
). With this function, you can pass multiple bits of data on the query string because objects can hold multiple values and as a result, this is more versatile than the other functions.
File: RGraph.common.core.js(array) RGraph.GET.array(name[, separator])
Fetches an array from the query string. Your array may or may not have the enclosing square brackets and you can pass an optional second string argument that will be used as the separator.
File: RGraph.common.core.js
Clipping functions
version 6.17
) a new clip
property that has been added to both the canvas
and svg
chart types which eliminates the need to use these clipping functions and is a lot easier for you to add to your charts. You can read about the clip configuration property here. -
(void) RGraph.clipTo.start(obj, path)
This function can be used to clip thecanvas
(which, using the standardcanvas
api
functions, can be a somewhat verbose procedure) in order to facilitate a variety of things including multi-colorLine charts
(there are demos of such charts in the download archive calledline-clipping1.html
line-clipping2.html
line-clipping3.html
andline-clipping4.html
). The second argument can be a string or an array and there are examples of each way that you can use the function shown below. Because, using this technique, the clipping starts before RGraph applies an antialiasing fix and then thecanvas
is restored to that state, the second chart may not be correctly antialiased. If this is the case then you may need to add this line of code between the drawing of each your chart to reset the antialiasing flag that RGraph uses:// Sometimes this may be necessary to reset the antialiasing fix that RGraph applies to the canvas obj.canvas.__rgraph_aa_translated__ = false;
Normally though,RGraph will accommodate this and the fix will not be necessary.
Example 1 - clipping to half of the canvas
Note: The
tophalf
/bottomhalf
/lefthalf
/righthalf
options do now take into account the fact that you may have different margin sizes. This means that you could have amarginTop
value of150
and amarginBottom
value of10
and the cutoff point will st ill be in the center of the chart.var data = [8,4,6,5,3,-5,-4,-8,-6,-3,4,5,9]; new RGraph.Line({ id: 'cvs', data: data, options: { colors: ['green'], xaxisPosition: 'center' } }).on('beforedraw', function (obj) { RGraph.clipTo.start(obj, 'tophalf'); // RGraph.clipTo.start(obj, 'bottomhalf'); // RGraph.clipTo.start(obj, 'lefthalf'); // RGraph.clipTo.start(obj, 'righthalf'); }).on('draw', function (obj) { RGraph.clipTo.end(); }).draw(); new RGraph.Line({ id: 'cvs', data: data, options: { colors: ['red'], xaxisPosition: 'center' } }).on('beforedraw', function (obj) { RGraph.clipTo.start(obj, 'bottomhalf'); }).on('draw', function (obj) { RGraph.clipTo.end(); }).draw();
Example 2 - clipping to a rectangle (x/y/width/height)
var data = [8,4,6,5,3,-5,-4,-8,-6,-3,4,5,9]; new RGraph.Line({ id: 'cvs', data: data, options: { xaxisPosition: 'center' } }).on('beforedraw', function (obj) { RGraph.clipTo.start(obj, [0,0,700,150]); }).on('draw', function (obj) { RGraph.clipTo.end(); }).draw();
Example 3 - clipping to an RGraph path string (a circle in this case)
var data = [8,4,6,5,3,-5,-4,-8,-6,-3,4,5,9]; new RGraph.Line({ id: 'cvs', data: data, options: { xaxisPosition: 'center' } }).on('beforedraw', function (obj) { RGraph.clipTo.start(obj, 'b a 50 50 25 0 6.29 false'); }).on('draw', function (obj) { RGraph.clipTo.end(); }).draw();
Example 4 - clipping to a formatted RGraph path string (a circle in this case)
var data = [8,4,6,5,3,-5,-4,-8,-6,-3,4,5,9]; new RGraph.Line({ id: 'cvs', data: data, options: { xaxisPosition: 'center' } }).on('beforedraw', function (obj) { RGraph.clipTo.start(obj, 'b a %1 %2 %3 %4 %5 false'.format(50,50,25,0,6.29)); }).on('draw', function (obj) { RGraph.clipTo.end(); }).draw();
Example 5 - clipping to a formatted (with an array of arguments) RGraph path string (a circle in this case)
var data = [8,4,6,5,3,-5,-4,-8,-6,-3,4,5,9]; new RGraph.Line({ id: 'cvs', data: data, options: { xaxisPosition: 'center' } }).on('beforedraw', function (obj) { RGraph.clipTo.start(obj, 'b a %1 %2 %3 %4 %5 false'.format([50,50,25,0,6.29])); }).on('draw', function (obj) { RGraph.clipTo.end(); }).draw();
Example 6 - clipping to an array of x/y coordinates (that create a shape)
var coords = [[0,0],[20,150],[40,250],[20,270],[0,270]]; var data = [8,4,6,5,3,-5,-4,-8,-6,-3,4,5,9]; new RGraph.Line({ id: 'cvs', data: data, options: { xaxisPosition: 'center' } }).on('beforedraw', function (obj) { RGraph.clipTo.start(obj, coords); }).on('draw', function (obj) { RGraph.clipTo.end(); }).draw();
Example 7 - clipping to two horizontal sections (starting on the left, finishing on the right, the top half is green and the bottom half is red)
var data = [8,4,6,5,3,-5,-4,-8,-6,-3,4,5,9]; new RGraph.Line({ id: 'cvs', data: data, options: { colors: ['green'], xaxisPosition: 'center' } }).on('beforedraw', function (obj) { RGraph.clipTo.start(obj, 'y:-5%-50%'); }).on('draw', function (obj) { RGraph.clipTo.end(); }).draw(); new RGraph.Line({ id: 'cvs', data: data, options: { colors: ['red'], xaxisPosition: 'center', yaxisLabels: false } }).on('beforedraw', function (obj) { RGraph.clipTo.start(obj, 'y:50%-105%'); }).on('draw', function (obj) { RGraph.clipTo.end(); }).draw();
Example 8 - clipping to three vertical bars (with each bar starting at the top, finishing at the bottom)
// These options are used by all three
File: RGraph.common.core.jsLine chart
objects OPTIONS = { textSize: 15, xaxisPosition: 'center', yaxis: false, backgroundGridHlinesCount: 10, backgroundGridVlines: false, backgroundGridBorder: false, shadow: false, linewidth: 0.5, colors: ['red'], filled: true, filledColors:['rgba(255,128,128,0.25)'], marginInner: 15, spline: true, xaxisLabels: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'], xaxisTickmarksCount: 12 }; var DATA = [6,4,-3,-8,-10,-5,6,4,5,1,2,3,4,6]; new RGraph.Line({ id: 'cvs', data: DATA, options: OPTIONS }).on('beforedraw', function (obj) { RGraph.clipTo.start(obj, [0,0,300,250]); }).on('draw', function (obj) { RGraph.clipTo.end(); }).draw(); new RGraph.Line({ id: 'cvs', data: DATA, options: { ...OPTIONS, colors: ['yellow'], filledColors: ['rgba(255,255,128,0.5)'], yaxisLabels: false, xaxisLabels: null } }).on('beforedraw', function (obj) { RGraph.clipTo.start(obj, [300,0,300,250]); }).on('draw', function (obj) { RGraph.clipTo.end(); }).draw(); new RGraph.Line({ id: 'cvs', data: DATA, options: { ...OPTIONS, colors: ['#0f0'], filledColors: ['rgba(128,255,128,0.25)'], yaxisLabels: false, xaxisLabels: null } }).on('beforedraw', function (obj) { RGraph.clipTo.start(obj, [600,0,300,250]); }).on('draw', function (obj) { RGraph.clipTo.end(); }).draw(); -
(void) RGraph.clipTo.end()
Complements the above function and ends clipping. See above for examples of use.
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-
(mixed) RGraph.arrayClone(array[, objects = false[maxDepth = 5]])
Creates a copy of the givenobject
orarray
. The implementation of this function has changed in theversion 6.18
release. Instead of using theJSON.parse(JSON.stringify(obj))
method it now loops through each element copying it or recursing into it (in the case of anarray
or anobject
) and "manually" copying it to the newarray
(orobject
).
var original_array = [4,6,8,['blah',44,7,null],3,2,5]; var myCopy1 = RGraph.arrayClone(original_array, true);
At some point in the future the default value for theobjects
parameter will be changed totrue
but for now, if you want to cloneobjects
as well asarrays
then you must set this parameter totrue
.
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 that 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 standardjavascript
concat
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/groupedbar 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
-
(array) RGraph.arrayRemoveNull(array[, options])
When you pass this function anarray
or anobject
thenull
values in it will be removed. By default, objects aren't touched however if you give anobject
as the second argument which has the keyobjects
(for exampleRGraph.arrayRemoveNull(myArray, {objects: true})
) thennull
values will be removed from objects too. If you give avalue
parameter to the options arraynull
values will NOT be removed, but substituted with that value instead.
File: RGraph.common.core.js
<script> myArray = [1, 1, null, {a: 1, b:null}]; arr = RGraph.arrayRemoveNull(myArray, {objects: true,value: 'XXX'}); console.log(arr); // Result: [1, 1, 'XXX', {a: 1, b:'XXX'}] arr2 = RGraph.arrayRemoveNull(myArray); console.log(arr2); // Result: [1, 1, {a: 1, b: null}] </script>
-
(mixed) RGraph.arrayLast()
This function provides an easy way to get the last item of anarray
. An example of its usage:var myArray = [8,4,6,5,3,5,1]; var last_element = RGraph.arrayLast(myArray); // 1
Another easy way would be to use thejavascript
at
function like this:var myArray = [8,4,6,5,3,5,1]; var last_element = myArray.at(-1); // 1
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 floating point number. The prepend and append options are strings that 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
-
(object) RGraph.parseConfigString(string[, separator = ','])
This function parses a configuration string into ajavascript
object. The separator argument is the character on which to split the string. So if you have a string like this:name=value,name2=value2,name3="A quoted value with spaces"
This function will parse it and return you an object:{ name: value, name2: value2 name3: A quoted value with spaces }
-
(string) RGraph.clearEventListeners(id)
This is the function to use if you want to clear thecanvas
or window officialdom2
event listeners (eg that facilitates things like tooltips). The id argument that you pass it should be either theid
of thecanvas
(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 allcanvas
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 from changing when thecanvas
is removed from the document. It removes thecanvas
from the document, replaces it with adiv
and then adds thecanvas
as a child node of thediv
. Thecanvas
is placed in the center of thediv
.
File: RGraph.common.effects.js (null) RGraph.pr(mixed)
Emulates thephp
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) $c(mixed)
Another (even shorter) 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 thecanvas
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 thecanvas
- the last chart that you created) has theclearto
option specified (egobj.set('clearto', 'white')
) then this function will use that color when clearing thecanvas
- essentially a default clear color.
File: RGraph.common.core.js -
(null) RGraph.clearAnnotations(canvas)
This function clears the annotation data associated with the givencanvas
(but DOES NOT redraw the chart). If you want to clear the visible annotations too, you will need to redraw thecanvas
. 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 thecanvas
. 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 thecanvas
) 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 thecanvas
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.units.pre
These units are placed before the numberscale.units.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 that's used to indicate a decimal point (default is . )scale.thousand
The character that's 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(mixed)
This function is used in conjunction with the next to register acanvas
for redrawing.canvas
tags 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 onecanvas
. The argument should be an RGraph object or from January 2022 it can also be a regular function. If it's a function then it will be run when theRGraph.redraw
function is run (not theRGraph.redrawCanvas
function).
File: RGraph.common.core.js
-
(null) RGraph.redraw([color])
This function is used in conjunction with the previous to redraw acanvas
.canvas
tags are redrawn (for example) when tooltips or crosshairs are being used.
Note: Allcanvas
tags that are registered are redrawn. The optional argument is the color to use when clearingcanvas
tags.
File: RGraph.common.core.js
-
(null) RGraph.redrawCanvas(canvas)
Similar to theredraw
function but only redraws the specifiedcanvas
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 theRGraph.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 the performance of your page. 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 separately from the page loading. As such, the placement of yourcanvas
tag becomes more important. What you can do is define thecanvas
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 thecanvas
. 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 from accumulating. It also clears theObjectRegistry
for the specificcanvas
- so if you use onecanvas
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 how to use this function 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 than 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 (today's 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 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 can also optionally take one argument - acanvas
id
- to limit the clearing to a particularcanvas
.
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 is a function that does the reverse of the above function and convertsradians
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 endpoint 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 thecanvas
. Thecanvas
is rotated about the X/Y coordinates that you give by the angle (which is measured inradians
). Angles can be negative.
File: RGraph.common.core.js
Other
These are less generic functions and are 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 that\'s 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
- Thelinewidth
used to draw the bounding boxbold
- Whether the text is bold or notmarker
- Whether to show a positioning markerhalign
- The horizontal alignment of the text. This can be left, center or right.valign
- The vertical alignment of the text. This can be bottom, center, top or now (from the January 2022 release) it can also be alphabetic.-
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 accessibledom
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, accessible: false, tag: 'myTag' });
-
(array) RGraph.text.find(options)
If you use accessible text then you can use this function to retrieve the actualdom
nodes (that arespan
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
- Theid
of thecanvas
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 thecanvas
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.
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 that 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 chart
,
Gantt chart
, Line chart
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 chart
/ Bar chart
/ Scatter chart
).
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 loaded yet. Therefore when the image IS loaded, the RGraph
drawBackgoundImage
function does a redraw
so that the image is painted onto 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, it 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
(mixed) RGraph.runOnce(id, func)
As the name suggests this function runs the given function once and once only (even if it's in a loop). It works by keeping a record of the
id
that
you give (which should be a string
) and if it's been
given that id
before then it simply returns
without running the function. There's no delay involved
in running the function - if that id
hasn't
been seen before it runs immediately. It returns whatever
the function returns.
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.
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 chart
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
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 chart
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.ORAn 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 samecanvas
otherwise ALL of the objects that you have created will be drawn when you redraw thecanvas
.
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 acanvas
tagid
(a string) or the actualcanvas
tag itself (as returned bydocument.getElementById
) and the clearing of theObjectRegistry
will be limited to thatcanvas
.
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 that 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 theid
of acanvas
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 that 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 object's 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 onto 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.