- Created on Friday, 25 February 2011 07:56
- Last Updated on Monday, 07 November 2016 06:53
- Written by Terrence
- Hits: 8701
There are lots of ways to draw graphs on a web page. Usually we use Flash for graphs all the time, but that has the limitation of not working on some mobile devices like the iPad or iPhone. There are server-side solutions that work well, but those might be too processor-intensive if you're working with real-time data.
RGraph is a HTML5 canvas graph library based on the canvas tag. Like most graph library, RGraph support wide variety of graph types including bar chart, pie chart, radar chart, etc.
Here's the code for a very simple bar graph:
Drawing Simple Graph
Download the Rgraph html 5.0 canvas libraries, and place the files in libraries folder into the 'js' folder.
We're using bar graph, so we need both the RGraph Bar graph library and the core RGraph library. We'll also use jQuery to grab the data out of the document. In the head section of the HTML page, we need to load the libraries we need.
chart.gutter-Outside area of the X and Y axis - where the labels go.
chart.title-Title of the Chart
- chart.labels-An array of the labels to be used on graph.
Describing Data with HTML
We' re using the HTML5 data attributes to store the browser names and the percentages. Although we have that information in the text.
Turning HTML into Graph
First, on line 2, we grab the text for the header. Then, on line 4, we select all the elements that have the data-name attribute. We use jQueryâ€™s map function to turn the values from those elements into an array.
We use that same logic again on line 8 to grab an array of the percentages.
We simply leave the data outside the canvas and then hide it with jQuery once weâ€™ve checked that the canvas exists.