Share: Bookmark with delicious tweet this site Post to Facebook

RGraph: HTML5 canvas graph library - Setting the width and height of your graph

[No canvas support]

Until 31st December 2010 the entire canvas was used for the graph, with only the chart.gutter space used for labels. You could increase the usable space by using the standard 2D context method translate(), however this was still not entirely suitable for all cases, for example where labels were large.

Now, however, you can set the usable width and height with chart.width and chart.height. This means that you could have a canvas that is 300 pixels high, but the area used by the graph is only 250 pixels high. Thus you will have the bottom gutter of the graph plus an extra 50 pixels for the labels. This is shown on the right.

Right aligning your graph

By default, because the coordinates start in the top left of the canvas, your graph will appear in the top left of the canvas too. If you want to change this and have your graph aligned to the right of the canvas you can use the standard 2D context method translate(). Typically, this would be useful if you have a large Y scale.

<script>
    myBar = new RGraph.Bar('cvs', [0.2,0.2,0.5,0.6,0.5,0.3,0.5,0.1,0.2,0.7,4.2,3.5]);
    myBar.Set('chart.ymax', 5);
    myBar.Set('chart.width', 600);
    myBar.Set('chart.height', 250);
    myBar.Set('chart.labels', ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']);
    myBar.Set('chart.tooltips', ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']);
    myBar.Set('chart.tooltips.coords.adjust', [35,0]);
    myBar.Set('chart.text.angle', 45);
    myBar.Set('chart.contextmenu', [['Zoom in', RGraph.Zoom]]);
    myBar.Set('chart.zoom.hdir', 'left');
    myBar.Set('chart.title', '2010 statistics (tooltips)');
    myBar.Set('chart.ylabels.specific', ['100,000','10,000','1,000','100','10']);
    myBar.Set('chart.background.grid.autofit', true);
    myBar.Set('chart.background.grid.autofit.align', true);
myBar.context.translate(35, 0);
myBar.Draw(); </script>

Resizing your graph

Resizing your graph causes the transformation state to be reset (ie any .translate() you have performed will be reset). You will therefore need to use the onresizebeforedraw event to translate again. This event fires after the canvas has been resized, but before the graph is redrawn. Eg:

RGraph.AddCustomEventListener(myObj, 'onresizebeforedraw', function (obj) {obj.context.translate(35, 0);});

If you're doing this you will probably also want to set the property chart.resizing.handle.adjust appropriately so that the resize handle is positioned correctly. Eg:

myBar.Set('chart.resize.handle.adjust', [-35, 0]);