Creating line graphs with Javascript using an HTML canvas

Creating line graphs with Javascript using an HTML canvas

learn how to create line graphs in Javascript to visually display your data using an HTML canvas


The canvas element (new to HTML5) is used to draw 2D graphics into an


HTML document. Using Javascript you can draw a wide range of objects


into an HTML canvas such as lines, text, images and shapes using several


built in function.


One of the uses of the canvas is element is the visualization of data. By making use of the graphics functions provided in Javascript, you can create graphing functions that visualize a given set of data.


In this tutorial you will learn how to create a line graph function that takes a dynamically sized array that contains each piece of data, and transforms that data into graph form.


You will need to have a basic understanding of

using the canvas element to draw lines

in order to properly understand this tutorial.


Drawing an outline for the graph using Javascript


When creating a graph, the first thing you will need to do is create the initial outline. In this tutorial we will be drawing the X and Y axis, as well as horizontal reference lines to help see the values of particular points on the graph.


Firstly, you will need to add a new canvas element into your HTML document, here we will make one with a width of 550, and a height of 450.


<canvas></canvas id="testCanvas" width="550" height="450">


Next we'll create the X and Y axis lines as well as the horizontal reference lines using Javascript. We'll also be leaving a margin of 25 pixels on the top and left sides of the graph for padding and a 75 pixel margin on the bottom and right sides of the graph for any extra information such as titles and reference values.


Taking these margins into account, our graph will start from 25:25 and end at 475:375, we'll declare these coordinates as well as the height and width of the graph as variables for reference throughout the tutorial .


var canvas = document.getElementById( "testCanvas" );  
var context = canvas.getContext( "2d" );  
   
// declare graph start and end  
var GRAPH_TOP = 25;  
var GRAPH_BOTTOM = 375;  
var GRAPH_LEFT = 25;  
var GRAPH_RIGHT = 475;   
   
var GRAPH_HEIGHT = 350;   
var GRAPH_WIDTH = 450;  
   
// clear canvas (if another graph was previously drawn)  
context.clearRect( 0, 0, 500, 400 );   
   
// draw X and Y axis  
context.beginPath();  
context.moveTo( GRAPH_LEFT, GRAPH_BOTTOM );  
context.lineTo( GRAPH_RIGHT, GRAPH_BOTTOM );  
context.lineTo( GRAPH_RIGHT, GRAPH_TOP );  
context.stroke();  
   
// draw reference line at the top of the graph  
context.beginPath();   
// set light grey color for reference lines  
context.strokeStyle = "#BBB";  
context.moveTo( GRAPH_LEFT, GRAPH_TOP );  
context.lineTo( GRAPH_RIGHT, GRAPH_TOP );  
context.stroke();  
   
// draw reference line 3/4 up from the bottom of the graph  
context.beginPath();  
context.moveTo( GRAPH_LEFT, ( GRAPH_HEIGHT ) / 4 * 3 + GRAPH_TOP );  
context.lineTo( GRAPH_RIGHT, ( GRAPH_HEIGHT ) / 4 * 3 + GRAPH_TOP );  
context.stroke();  
   
// draw reference line 1/2 way up the graph  
context.beginPath();  
context.moveTo( GRAPH_LEFT, ( GRAPH_HEIGHT ) / 2 + GRAPH_TOP );  
context.lineTo( GRAPH_RIGHT, ( GRAPH_HEIGHT ) / 2 + GRAPH_TOP );  
context.stroke();  
   
// draw reference line 1/4 up from the bottom of the graph  
context.beginPath();  
context.moveTo( GRAPH_LEFT, ( GRAPH_HEIGHT ) / 4 + GRAPH_TOP );  
context.lineTo( GRAPH_RIGHT, ( GRAPH_HEIGHT ) / 4 + GRAPH_TOP );  
context.stroke();

This will result in a graph outline that looks like this:


Drawing a graph outline with Javascript


Transforming data into lines in your graph using Javascript


Now that you've created a graph outline, you can start adding points in your graph and adding lines in-between them to create a line graph, for this we will use a single path.


The X position for each point on the line graph will be calculated by the graph width divided by the number of pieces of data, multiplied by the point's position in the array. The Y position for each point will be calculated by the graph height minus the point's actual value, divided by the largest piece of data in the set, multiplied by the graph height.


We will use the following Javascript to create the lines on our graph:


// declare test data set and get length   
var dataArr = [ 6, 8, 10, 12, 11, 7, 5, 8 ];  
var arrayLen = dataArr.length;  
   
// calculate largest piece of data  
var largest = 0;  
for( var i = 0; i < arrayLen; i++ ){  
    if( dataArr[ i ] > largest ){  
        largest = dataArr[ i ];  
    }  
}  
  
context.beginPath();   
// make your graph look less jagged  
context.lineJoin = "round";  
context.strokeStyle = "black";   
// add first point in the graph  
context.moveTo( GRAPH_LEFT, ( GRAPH_HEIGHT - dataArr[ 0 ] / largest * GRAPH_HEIGHT ) + GRAPH_TOP );   
// loop over data and add points starting from the 2nd index in the array as the first has been added already  
for( var i = 1; i < arrayLen; i++ ){  
    context.lineTo( GRAPH_RIGHT / arrayLen * i + GRAPH_LEFT, ( GRAPH_HEIGHT - dataArr[ i ] / largest * GRAPH_HEIGHT ) + GRAPH_TOP );  
}   
// actually draw the graph  
context.stroke();

This will result in a line graph that looks like this:


Drawing line graph data with Javascript


Adding reference values and putting it all together


Now that you've drawn your line graph, you will need to add reference values along the X and Y axis, as with the current graph it is difficult to tell what data is being shown and the value of each point. To fix this, we'll make use of the

fillText()

function to draw text displaying the reference values along the X and Y axis.


For this example we'll assume the X axis displays the days of the week (from 1-7) and the Y axis displays the number of hours worked by a certain employee.


We'll put all our Javascript for creating the graph inside a function to give it some re-usability.


function drawGraph( dataArr ){  
    var canvas = document.getElementById( "testCanvas" );  
    var context = canvas.getContext( "2d" );  
  
    var GRAPH_TOP = 25;  
    var GRAPH_BOTTOM = 375;  
    var GRAPH_LEFT = 25;  
    var GRAPH_RIGHT = 475;  
  
    var GRAPH_HEIGHT = 350;  
    var GRAPH_WIDTH = 450;  
  
    var arrayLen = dataArr.length;  
  
    var largest = 0;  
    for( var i = 0; i < arrayLen; i++ ){  
        if( dataArr[ i ] > largest ){  
            largest = dataArr[ i ];  
        }  
    }  
  
    context.clearRect( 0, 0, 500, 400 );  
    // set font for fillText()  
    context.font = "16px Arial";  
       
    // draw X and Y axis  
    context.beginPath();  
    context.moveTo( GRAPH_LEFT, GRAPH_BOTTOM );  
    context.lineTo( GRAPH_RIGHT, GRAPH_BOTTOM );  
    context.lineTo( GRAPH_RIGHT, GRAPH_TOP );  
    context.stroke();  
       
    // draw reference line  
    context.beginPath();  
    context.strokeStyle = "#BBB";  
    context.moveTo( GRAPH_LEFT, GRAPH_TOP );  
    context.lineTo( GRAPH_RIGHT, GRAPH_TOP );  
    // draw reference value for hours  
    context.fillText( largest, GRAPH_RIGHT + 15, GRAPH_TOP);  
    context.stroke();  
   
    // draw reference line  
    context.beginPath();  
    context.moveTo( GRAPH_LEFT, ( GRAPH_HEIGHT ) / 4 * 3 + GRAPH_TOP );  
    context.lineTo( GRAPH_RIGHT, ( GRAPH_HEIGHT ) / 4 * 3 + GRAPH_TOP );  
    // draw reference value for hours  
    context.fillText( largest / 4, GRAPH_RIGHT + 15, ( GRAPH_HEIGHT ) / 4 * 3 + GRAPH_TOP);  
    context.stroke();  
   
    // draw reference line  
    context.beginPath();  
    context.moveTo( GRAPH_LEFT, ( GRAPH_HEIGHT ) / 2 + GRAPH_TOP );  
    context.lineTo( GRAPH_RIGHT, ( GRAPH_HEIGHT ) / 2 + GRAPH_TOP );  
    // draw reference value for hours  
    context.fillText( largest / 2, GRAPH_RIGHT + 15, ( GRAPH_HEIGHT ) / 2 + GRAPH_TOP);  
    context.stroke();  
   
    // draw reference line  
    context.beginPath();  
    context.moveTo( GRAPH_LEFT, ( GRAPH_HEIGHT ) / 4 + GRAPH_TOP );  
    context.lineTo( GRAPH_RIGHT, ( GRAPH_HEIGHT ) / 4 + GRAPH_TOP );  
    // draw reference value for hours  
    context.fillText( largest / 4 * 3, GRAPH_RIGHT + 15, ( GRAPH_HEIGHT ) / 4 + GRAPH_TOP);  
    context.stroke();  
  
    // draw titles  
    context.fillText( "Day of the week", GRAPH_RIGHT / 3, GRAPH_BOTTOM + 50);  
    context.fillText( "Hours", GRAPH_RIGHT + 30, GRAPH_HEIGHT / 2);  
  
    context.beginPath();  
    context.lineJoin = "round";  
    context.strokeStyle = "black";  
  
    context.moveTo( GRAPH_LEFT, ( GRAPH_HEIGHT - dataArr[ 0 ] / largest * GRAPH_HEIGHT ) + GRAPH_TOP );  
    // draw reference value for day of the week  
    context.fillText( "1", 15, GRAPH_BOTTOM + 25);  
    for( var i = 1; i < arrayLen; i++ ){  
        context.lineTo( GRAPH_RIGHT / arrayLen * i + GRAPH_LEFT, ( GRAPH_HEIGHT - dataArr[ i ] / largest * GRAPH_HEIGHT ) + GRAPH_TOP );  
        // draw reference value for day of the week  
        context.fillText( ( i + 1 ), GRAPH_RIGHT / arrayLen * i, GRAPH_BOTTOM + 25);  
    }  
    context.stroke();  
}   
   
// test graph  
var testValues = [ 0, 6, 8, 7, 5, 6, 5 ];  
drawGraph( testValues );

The line graph created for this example looks like this:


Javascript line graph example with reference values


Now you should be able to create your own line graphs using Javascript to visually display your data. You can also modify the width and height of your canvas as well as the style of your graph to suit your needs.


Other data visualization tutorials:


-

Creating pie charts with Javascript using an HTML canvas

.



Instructobit Thornton@Instructobit 3 years ago
or