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:
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 zoom functions reside in RGraph.common.zoom.js,
so if you don't need zoom, 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 example. If you want to create your own
chart type you can use one of the drawing objects as a starting point.
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>
window.onload = function ()
{
// 1/2 First draw the chart
var myBar = new RGraph.Bar('myCanvas', [1,5,8,4,6,3,1,5,7,8,4,6]);
myBar.Set('chart.labels', ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']);
myBar.Draw();
// 2/2 Now get hold of the references
var context = myBar.context; // Get hold of a reference to the context
var canvas = myBar.canvas; // Get hold of a reference to the canvas
}
</script>
The RG, ca, co and prop variables
Because local variables are a very fast type of variable - RGraph is adopting the use of these variables
thoughout all of the libraries. You'll see these as RG, ca, co and prop -
and they're just short names for the RGraph "class", the canvas, the context and the objects properties.
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 object adds a reference to the object to the
canvas and you can access it like this:
<script>
document.getElementById("myCanvas").onclick = function (e)
{
var src = (RGraph.isIE8() ? event.srcElement) : e.target;
// The RGraph object constructors add __object__ to the canvas.
var myBar = src.__object__;
}
</script>
Working with chart coordinates
For most chart types, the coordinates of elements (eg bars, lines etc) are to be found in the class variable obj.coords.
This is usually a multi-dimensional array consisting of the coordinates of those shapes, or of 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 coords array is
usually a flat array, even when you have multiple sets of data.
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 myCoords = myBar.coords;
Note: Previously the coords array values sometimes included the margin values, and sometimes didn't. As of 17th
April 2010 the values have all been unified to not include the margin values, so the values are as reported.
Note:
The Line chart also has an object variable myObj.coords2, where the coordinates are indexed differently -
by line index.
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 class variable 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 associate data variables are listed below1.
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 in obj.original_data[0], the second in obj.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() or parseInt() functions. For example:
<script>
num = Number('23');
num = parseInt('43');
</script>
The May 2013 release added AJAX helper funcions 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[, seperator])
RGraph.AJAX.getJSON(url, callback)
RGraph.AJAX.POST(url, data, callback)
A common request is to be able to update charts dynamically. This is quite simple and consists of three steps:
Get the new data from the server (with an AJAX request for example).
Set the data in your chart object. See the above table for the appropriate property to use.
Call the .Draw() method again.
If you don't need to get data from your server (ie it's all client-side) then you can omit the first step. Also, it may be
sufficient to simply recreate the entire object from scratch. This means that you won't have to alter any
RGraph internal properties - just recreate the chart object and configuration. There's a simple function
you can use for AJAX purposes here.
Setting properties
To set RGraph properties, ideally you should use each objects setter (there's also a corresponding getter). These functions
accomodate some backwards compatibility changes, so by not using them you run the risk of your charts not working entirely as
expected.
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 are stored. Typically the objects are named with the format __xxx__, and you can inspect the
objects by using a console(eg the inspector that's part of Google Chrome - CTRL+SHIFT+J). Some examples are:
__object__ on the canvas - a reference to the chart object
RGraph.Registry.Get('chart.tooltip') - a reference to the currently visible tooltip. This in turn has the following
available:
__text__ - Since setting .innerHTML 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 the Scatter chart and corresponding to the dataset.
__canvas__ - A reference to the original canvas that triggered the tooltip.
RGraph.Registry.Get('chart.mousedown') - Used in annotating, and stipulates whether the mouse button is currently
pressed.
RGraph.Registry.Get('chart.contextmenu') - The currently shown context menu, if any. This in turn has the following
properties:
__canvas__ - The original canvas object.
These are just a sample of what's available, to find more you should use an introspection tool or look at the source.
Scale information
For the Bar, Bipolar, HBar, Line and Scatter charts the scale that is used is stored in the scale class variable. Eg:
<script>
var myBar = new RGraph.Bar('cvs', [56,43,52,54,51,38,46,42,52]);
myBar.Draw();
var myScale = myBar.scale
</script>
Adding text to your charts
If you want to add arbitrary text to your chart(s) you can either use
the Text drawing API object or use
the RGraph functions directly. The drawing API object has advantages in
that it supports you 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 aabout using the ondraw event.
RGraph functions
This is a list of some of the functions available to you in the RGraph common libraries.
It's not every single one that's available, but is a list of the common ones that you're likely to want to use. Arguments
in square brackets are optional.
(number) RGraph.array_max(array) Returns the maximum value in the array. File: RGraph.common.core.js
(number) RGraph.array_sum(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.array_clone(array) Creates a copy/clone of the given array. Only numerically indexed arrays are supported. File: RGraph.common.core.js
(array) RGraph.array_reverse(array) Returns a reversal of the given array. File: RGraph.common.core.js
(boolean) RGraph.is_array(obj) Returns true or false as to whether the given object is an array or not. File: RGraph.common.core.js
(array) RGraph.array_pad(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.array_shift(array) Shifts an element off of the start of the given array and returns the new array. File: RGraph.common.core.js
(array) RGraph.array_linearize(arr1, arr2, arr3, ...)
This function takes any number of arrays as arguments and concatenates them all into on big array. Similar to the standard
Javascript .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 n3eed to convert into 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]
(array) Array.forEach(callback)
This is an emulation of the newer Array.forEach() function. This function calls the given callback for each element of the
array. The callback is a normal function that is passed three arguments: value, index, array. This allows you to
modify the element if necessary by using the array and index options. If you do modify the array the elements are changed
for subsequent iterations through the array.
(string) RGraph.rtrim(string) Strips the right hand white space from the string that you pass it. File: RGraph.common.core.js
(string) RGraph.number_format(obj, number[, prepend[, append]])
This formats the given number (which can be either an integer or a float. The prepend and append variables are
strings which are added to the string (eg 5%).
Note:As of 5th September 2010 this functions argument list has been changed to include the chart object, as shown above.
File: RGraph.common.core.js
Numbers
(number) RGraph.random(min, max) Returns a random number between the minimum and maximum that you give. File: RGraph.common.core.js
(string) RGraph.number_format(obj, number[, prepend[, append]]) See above. File: RGraph.common.core.js
(number) RGraph.log(number, base) This function returns the logarithim 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 the ID of the canvas (the same as what you pass to
document.getElementById() ), or just 'window' 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 associated ObjectRegistry method: RGraph.ObjectRegistry.getObjectByUID()
which can then be used to retrieve an object with the UID.
File: RGraph.common.core.js
(object) RGraph.Effects.ReplaceCanvasWithDIV(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
(object) RGraph.FixEventObject(event) Pass this function an event object and it will attempt to "fill in" the missing properties (depending on the browser).
It tries to add:
pageX (MSIE)
pageY (MSIE)
target (MSIE)
stopPropagation() (MSIE)
offsetX (FF)
offsetY (FF)
File: RGraph.common.core.js
(null) RGraph.OldBrowserCompat(context) This function "fills in" any required functions that some browsers don't have. At the moment this consists of adding the measureText() and fillText() functions to the context when they're missing (usually this means older versions of Opera). File: RGraph.common.core.js
(number) RGraph.GetDays(date) This returns the number of days in the given month. The argument should be a Date object. File: RGraph.common.core.js
(null) RGraph.pr(mixed) Emulates the PHP function print_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 far shorter to type. File: RGraph.common.core.js
(null) cl(mixed)
A shortcut for the Firebug and Google Chrome debug function console.log(). File: RGraph.common.core.js
(number) AA(obj, number)
This function is used to help circumvent the canvas antialiasing by offsetting the given value to the nearest half pixel.
eg. A value of 25 becomes 25.5 File: RGraph.common.core.js
(null) RGraph.Clear(canvas[, color]) Clears the canvas by drawing a white (or the optional color you give) rectangle over it. As of 23rd January 2011 you can now specify transparent as the color and the canvas will be reset back to transparency instead of to white. This may become the default at a later date. 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(max, obj) Given the maximum value this will return an appropriate scale. The second argument is the graph object. File: RGraph.common.core.js
(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 RGraph
ObjectRegitsry 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.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.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
seperate 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. This is how the front page is coded,
(but not using the RGraph.Async() function).
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.
Note: Since a dev release of version 4, Google Chrome versions 4 and 5 have an issue with rendering text when using
the RGraph.Async() function. The solution here is to simply not use the RGraph.Async() function.
File: RGraph.common.core.js
(null) RGraph.filledCurvyRect(context, x, y, width, height[, radius[, curvy top left[, curvy top right[, curvy bottom right[, curvy bottom left]]]]])
This draws a rectangle with curvy 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 curvy. File: RGraph.common.core.js
(null) RGraph.strokedCurvyRect(context, x, y, width, height[, radius[, curvy top left[, curvy top right[, curvy bottom right[, curvy bottom left]]]]])
This draws a rectangle with curvy 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 curvy. 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, and so can stop them accumulating. As of November 2012 it
also clears the ObjectRegistry 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(obj, x1, y1, x2, y2, 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. As of October 2012 you can specify more than two colors if you wish. File: RGraph.common.core.js
(object) RGraph.RadialGradient(obj, x1, y1, r1, x2, y2, r2, 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. As of October 2012 you can specify more than two colors if you wish. File: RGraph.common.core.js
(null) RGraph.DrawYAxis(obj, options)
This function can be used to draw extra Y axes as required. It takes two arguments - the chart object and an associative
array/dictionary of options. These options can be:
chart.x - The X position (required)
chart.max - The maximum value (required)
chart.min - The minimum value (default: 0)
chart.context - Optionally you can specify a specific drawing context to use (default: null)
chart.color - The color of the axis (default: black)
chart.title - The title used for the axis (default none)
chart.title.color - The color of the title (default: black)
chart.text.color - The color of the axis labels (default: black)
chart.numlabels - Number of labels (default: 5)
chart.numticks - Number of tickmarks (default: 10)
chart.font - The font used (default: Arial)
chart.text.size - The size of the labels (default: 10)
chart.align - The alignment of the axes - left (default), or right
chart.scale.decimals - The number of decimals that are shown. (default: 0)
chart.scale.formatter
- You can use this to specify a function that formats the values on the scale. A sample function is:
function myFormatter(obj, num)
{
return num + 'F'; // An example of formatting
}
chart.units.pre - This can be used to specify pre units (default: Blank string).
chart.units.post - This can be used to specify post units (default: Blank string).
chart.noendtick.top - Whether to not draw the top end tickmark (default: false (ie it IS drawn)).
chart.noendtick.bottom - Whether to not draw the bottom end tickmark (default: false (ie it IS drawn)).
chart.noyaxis - Whether to not draw the axis or not (labels/titles still shown) (default: false (ie it IS drawn)).
(null) RGraph.DrawXAxis(obj, options)
This function can be used to draw extra X axes as required. It takes two arguments - the chart object and an associative
array of options. These options can be:
chart.y - The Y position of the axis(required)
chart.min - For use with a scaled axis this is the minimum value shown (default: 0)
chart.max - For use with a scaled axis this is the maximum value shown (default: none)
chart.context - Optionally you can specify a specific drawing context to use (default: null)
chart.labels - Instead of a scale you can instead show labels (default: none)
chart.labels.position - This can either be edge or section and stipulates where the labels are positioned (default: section)
chart.color - This is used as the color for the axes (default: black)
chart.text.color - This is used as the color for the text. If not specified it falls back to chart.color (default: black)
chart.text.size - The size of the text in points (default: 10)
chart.text.font - The font used to render the text (default: Arial)
chart.align - The vertical alignment of the text - top/bottom (default: bottom)
chart.numlabels - When scaled this is the number of labels shown (excluding 0) (default: 5)
chart.hmargin - If you're using a Line chart hmargin then you should set this to match it (default: 0)
chart.scale.formatter - This can be a user defined function that returns the formatted number for the scale (default: null)
function myFormatter(obj, num)
{
return num + 'F'; // An example of formatting
}
chart.scale.decimals - This is the number of decimals shown on the scale (default: 0)
chart.scale.invert - If true, this will invert the Y scale (so 0 on the left) (default: false)
chart.units.pre - This can be used to specify pre units (default: Blank string).
chart.units.post - This can be used to specify post units (default: Blank string).
chart.title - The title for the axes
chart.title.color - The color of the title. If not specified this falls back to chart.color (default: black)
chart.numticks - The number of tickmarks shown on the axis (default: 10)
chart.noendtick.left - Whether to not draw the left tickmark (default: false (ie it IS drawn)).
chart.noendtick.right - Whether to not draw the right tickmark (default: false (ie it IS drawn)).
chart.noxaxis - Whether to not draw the axis or not (labels/titles still shown) (default: false (ie it IS drawn)).
An example usage of the function would be:
RGraph.DrawXAxis(myLine, {
'chart.y': obj.canvas.height - obj.Get('chart.gutter.bottom'), // Position the axes at the bottom
'chart.title': 'Water pipe pressure',
'chart.title.color': 'gray',
'chart.color': 'gray',
'chart.text.color': 'gray',
//'chart.max': 10,
//'chart.min': 0,
'chart.labels': ['Q1','Q2','Q3','Q4'],
//'chart.scale.formatter': myFormatter,
'chart.align': 'bottom'
});
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, eg ontooltip, and the function argument is your function which handles the event. The return value is an ID which can be used with the RGraph.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 by RGraph.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
(number) RGraph.degrees2Radians(number)
Converts and returns the given number of degrees to radians. Roughly, 1 radian = 57.3 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 Pythagorous theorem 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(context, font, size, x, y, text[, valign[, halign[, border[, angle[, background[, bold[, indicator]]]]]]])
This function acts as a wrapper around the canvas text functionality. This function is now deprecated in favour of
the newer rewrite - RGraph.Text2() (as described next). The arguments are:
The context is the canvases context.
The font is the name of the font you want to use (eg Arial).
The size is an integer specifying the size of the text, (measured in points).
The x and y arguments are the X/Y coordinates at which to draw the text.
The text argument is the text to draw.
The optional valign argument is the vertical alignment and can be either top, center or bottom.
The optional halign argument is the horizontal alignment and can be left, center or right.
The optional border argument is a boolean (true or false) controlling whether the text has a border.
The optional angle argument specifies the angle at which the text is drawn (rotated around the X/Y coordinates and measured in degrees).
The optional background argument is the color of the background, (eg #fff).
The optional bold argument is boolean which controls whether the text is bold or not.
And the optional indicator argument is a boolean which controls whether a placement indicator is shown.
File: RGraph.common.core.js
(null) RGraph.Text2(obj, options)
This function is a rewrite of the original text function above. 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 the obj.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:
font - The font used to render the text
size - Th size of the text (in points)
x - The X position of the text
y - The Y position of the text
text - The text to display
bounding - Whether to draw a bounding box around the text
bounding.stroke - The strokeStyle of the bounding box
bounding.fill - The fillStyle of the bounding box
bounding.shadow - Whether the bounging box has a shadow
bounding.shadow.color - The color of the shadow
bounding.shadow.blur - The severity of the shadow blur
bounding.shadow.offsetx - The X offset of the shadow
bounding.shadow.offsety - The Y offset of the shadow
bounding.linewidth - The linewidth used to draw the bounding box
bold - Whether the text is bold or not
marker - Whether to show a positioning marker
halign - The horizontal alignment of the text
valign - 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 the
obj.coordsText array.
Note that the first object is normally the chart object - though it can also be a string containing the ID of the canvas,
the canvas (as returned by document.getElementById() or the the 2D context. The coords are always returned, though
they're only stored in the .coordsText array if you give an RGraph object.
File: RGraph.common.core.js
(null) RGraph.DrawTitle(object, text, gutter[, 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, idx, e) This function shows a tooltip. The idx value corresponds to the tooltip array that you give. The e 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.
Note: As of the November 2011 the key has been seperated out into its own file.
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:
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
(number) RGraph.getGutterSuggest(obj, data)
This function returns a suggested gutter setting based on the vertical labels. If the bottom labels are larger, this
setting may be inappropriate. The data variable is a simple single dimension array, eg [1,2,3,4,5].
var size = RGraph.getGutterSuggest(obj, data);
obj.Set('chart.gutter.left', size);
File: RGraph.common.core.js
(boolean) RGraph.isOld()
This function tests the useragent for MSIE 7 OR 8. File: RGraph.common.core.js
(boolean) RGraph.isIE8()
This function tests the useragent for MSIE8. File: RGraph.common.core.js
(boolean) RGraph.isIE8up()
This function tests the useragent for MSIE8 or higher. File: RGraph.common.core.js
(boolean) RGraph.isIE9()
This function tests the useragent for MSIE9. File: RGraph.common.core.js
(boolean) RGraph.isIE9up()
This function tests the useragent for MSIE9 or higher. File: RGraph.common.core.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:
chart.gutter
chart.variant
chart.text.size
chart.text.font
chart.title
chart.title.xaxis
chart.title.xaxis.pos
chart.title.yaxis
chart.title.yaxis.pos
chart.background.barcolor1
chart.background.grid
chart.background.grid.width
chart.background.grid.autofit
chart.background.grid.autofit.numhlines
chart.background.grid.autofit.numvlines
chart.background.grid.autofit.align
chart.background.grid.hlines
chart.background.grid.vlines
chart.background.grid.hsize
chart.background.grid.vsize
chart.background.grid.color
chart.background.grid.border
chart.background.barcolor2
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', myCallback);
function myCallback (str)
{
// Handle the reesponse and create the chart
}
</script>
(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('/getdata.html', myCallback);
function myCallback (str)
{
// Handle the reesponse and create the chart
}
</script>
(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', myCallback);
function myCallback (num)
{
// Handle the reesponse and create the chart
}
</script>
(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', myCallback);
function myCallback (json)
{
// Handle the reesponse and create the chart
}
</script>
(null) RGraph.AJAX.getCSV(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 array which is created from the first line of your
CSV data). You would use it like this:
<script>
RGraph.AJAX.getCSV('/getdata.html', myCallback);
function myCallback (csv)
{
// Handle the reesponse and create the chart
}
</script>
(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).
Creating your own chart type
If you want to create your own chart type using the RGraph system then you could use the Rect drawing object as a starting
point. It has many of the methods that RGraph uses (eg .Set, .Get, .Draw() ) and is also quite short and not overloaded
with extraneous code.
The RGraph ObjectRegistry
The RGraph ObjectRegistry is new in March 2012 and it 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 type 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>
window.onload = function (e)
{
var bar = new RGraph.Bar('cvs', [4,8,5,7,8,9]);
bar.Set('chart.labels', ['Alex','Doug','Charles','Nick','Michelle','Ali']);
bar.Set('chart.colors', ['#ffc']);
bar.Set('chart.tooltips', ['Alex','Doug','Charles','Nick','Michelle','Ali']);
var line = new RGraph.Line('cvs', [3,9,4,9,6,5]);
line.Set('chart.tickmarks', 'endcircle')
line.Set('chart.colors', ['black'])
line.Set('chart.linewidth', 2);
line.Set('chart.tooltips', ['1984','1985','1986','1987','1988','1989']);
// Create the combination object - this draws the chart for us
var combo = new RGraph.CombinedChart(bar, line);
combo.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 gutters 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 oertinent objects for a
given canvas, or one particular object if you need it. The following methods are available:
RGraph.ObjectRegistry.Add(object)
This method adds an object to the ObjectRegistry. It's used predominantly by the RGraph.Register) function. File: RGraph.common.core.js
RGraph.ObjectRegistry.Remove(object)
This method removes an object from the ObjectRegistry. 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 the ObjectRegistry 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 by document.getElementById()) and the clearing
of the ObjectRegistry will be limited to that canvas.
File: RGraph.common.core.js
RGraph.ObjectRegistry.ClearbyType(type)
This function is similar to the Clear() function but limits the clearing action to those objects of the
specified type.
File: RGraph.common.core.js
RGraph.ObjectRegistry.Iterate(function[, type(s)])
The Iterate function provides an easy way to go through all or some of the objects in the ObjectRegistry. The first
argument should be a function which is called for every matching object in the ObjectRegistry. By default this function
iterates through each object in the ObjectRegistry, 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 exmples 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 the ObjectRegistry.
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 with myObject.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 the ObjectRegistry that has that type.
File: RGraph.common.core.js
RGraph.ObjectRegistry.bringToFront(obj)
This method removes an object from the ObjectRegistry and readds it 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 documenred
here.