HTML5 Line Graph Using Canvas

Introduction

 
In this article, I will walk through how to create a Line Chart using HTML5 canvas.
 

What is a Line Chart?

 
A line chart is a style of chart that is created by connecting a series of data points together with a line. It is used to display information in a series of data points connected by straight line segments. It enables us to find trends (or patterns) over time.
 

Use of the Line Chart

 
A line graph is used to represent a set of data values in which a quantity varies with time. We can use a line chart to show how the stock value for a certain company develops over time on the stock market. We can also use it for representing temperature, sales, employment, company profit or cost over a period of time.
 
The figure given below represents how to create a line series with symbols in HTML5.
 
Figure 1 
 
linegraph.jpg
 
Browser Support
 
It is supported by all major browsers such as Internet Explorer 9, Firefox 3.6+, Safari 4+ and Chrome, etc.
 
Procedure for creating the Line Graph
 
Step 1
 
We first define the element using HTML5 canvas. The height and width attributes set the canvas and graph size.
 
<canvas id="myCanvas" width="600" height="300" style="border: 1px solid black;"></canvas>
 
Step 2
 
In order to interact with this canvas through JavaScript, we will need to first get the element by Id and then create a context.
  1. <script type="text/javascript">  
  2.     var canvas = document.getElementById('mycanvas');  
  3.     var ctx = canvas.getContext("2d");  
  4. </script> 
Step 3
 
In the following step, we will create a "LineChart()" function in which we define various methods, variables, constants, and properties.In this step, we will draw both the X-axis and Y-axis.
  1. function LineChart(con)  
  2. {  
  3.      // user defined properties  
  4.      this.canvas = document.getElementById(con.canvasId);  
  5.      this.minX = con.minX;  
  6.      this.minY = con.minY;  
  7.      this.maxX = con.maxX;  
  8.      this.maxY = con.maxY;  
  9.      this.unitsPerTickX = con.unitsPerTickX;  
  10.      this.unitsPerTickY = con.unitsPerTickY;  
  11.    
  12.       // constants  
  13.       this.padding = 10;  
  14.       this.tickSize = 10;  
  15.       this.axisColor = "#555";  
  16.       this.pointRadius = 5;  
  17.       this.font = "12pt Calibri";  
  18.    
  19.       this.fontHeight = 12;  
  20.    
  21.       // relationships       
  22.       this.context = this.canvas.getContext("2d");  
  23.       this.rangeX = this.maxX - this.minY;  
  24.       this.rangeY = this.maxY - this.minY;  
  25.       this.numXTicks = Math.round(this.rangeX / this.unitsPerTickX);  
  26.       this.numYTicks = Math.round(this.rangeY / this.unitsPerTickY);  
  27.       this.x = this.getLongestValueWidth() + this.padding * 2;  
  28.       this.y = this.padding * 2;  
  29.       this.width = this.canvas.width - this.x - this.padding * 2;  
  30.       this.height = this.canvas.height - this.y - this.padding - this.fontHeight;  
  31.       this.scaleX = this.width / this.rangeX;  
  32.       this.scaleY = this.height / this.rangeY;  
  33.    
  34.       // draw x y axis and tick marks  
  35.       this.drawXAxis();  
  36.       this.drawYAxis();  
Step 4
 
In the following step, we will get the value of the longest width of the following Line Graph or chart. For finding the longest value we apply the loop that will return the longest Value Width.
  1. LineChart.prototype.getLongestValueWidth = function ()  
  2. {  
  3.    this.context.font = this.font;  
  4.    var longestValueWidth = 0;  
  5.    for (var n = 0; n <= this.numYTicks; n++)  
  6.      {  
  7.        var value = this.maxY - (n * this.unitsPerTickY);  
  8.        longestValueWidth = Math.max(longestValueWidth, this.context.measureText(value).width);  
  9.      }  
  10.    return longestValueWidth;  
  11. }; 
Step 5
 
In this step, we will draw the line chart along the x-axis. We also draw the tick marks along the x-axis and finally in this step we draw the x-axis labels. For drawing both the tick marks and labels we apply the loop.
  1. LineChart.prototype.drawXAxis = function ()  
  2. {  
  3.    var context = this.context;  
  4.    context.save();  
  5.    context.beginPath();  
  6.    context.moveTo(this.x, this.y + this.height);  
  7.    context.lineTo(this.x + this.width, this.y + this.height);  
  8.    context.strokeStyle = this.axisColor;  
  9.    context.lineWidth = 2;  
  10.    context.stroke();  
  11.    
  12.    // draw tick marks  
  13.    for (var n = 0; n < this.numXTicks; n++)  
  14.     {  
  15.        context.beginPath();  
  16.        context.moveTo((n + 1) * this.width / this.numXTicks + this.x, this.y + this.height);  
  17.        context.lineTo((n + 1) * this.width / this.numXTicks + this.x, this.y + this.height - this.tickSize);  
  18.        context.stroke();  
  19.     } 
Figure 2
 
This figure represents tick mark along x-axis shown below
 
x axis.jpg
 
  1.    // draw labels  
  2.    context.font = this.font;  
  3.    context.fillStyle = "black";  
  4.    context.textAlign = "center";  
  5.    context.textBaseline = "middle";  
  6.    
  7.    for (var n = 0; n < this.numXTicks; n++)  
  8.     {  
  9.        var label = Math.round((n + 1) * this.maxX / this.numXTicks);  
  10.        context.save();  
  11.        context.translate((n + 1) * this.width / this.numXTicks + this.x, this.y + this.height + this.padding);  
  12.        context.fillText(label, 0, 0);  
  13.        context.restore();  
  14.     }  
  15.    context.restore();  
  16. }; 
Figure 3
 
This figure represents labels along the x-axis
 
x axis1.jpg
 
Step 6
 
Similarily, we will draw the line chart along the y-axis. We also draw the tick marks along the y-axis and finally in this step we draw the y-axis labels. For drawing both of the tick marks and labels we apply the loop.
  1. LineChart.prototype.drawYAxis = function ()  
  2. {  
  3.    var context = this.context;  
  4.    context.save();  
  5.    context.save();  
  6.    context.beginPath();  
  7.    context.moveTo(this.x, this.y);  
  8.    context.lineTo(this.x, this.y + this.height);  
  9.    context.strokeStyle = this.axisColor;  
  10.    context.lineWidth = 2;  
  11.    context.stroke();  
  12.    context.restore();  
  13.    
  14.    // draw tick marks  
  15.    for (var n = 0; n < this.numYTicks; n++)  
  16.     {  
  17.        context.beginPath();  
  18.        context.moveTo(this.x, n * this.height / this.numYTicks + this.y);  
  19.        context.lineTo(this.x + this.tickSize, n * this.height / this.numYTicks + this.y);  
  20.        context.stroke();  
  21.     } 
Figure 4
This figure shows the tick mark along the y-axis:
y axis.jpg
  1.    // draw values  
  2.    context.font = this.font;  
  3.    context.fillStyle = "black";  
  4.    context.textAlign = "right";  
  5.    context.textBaseline = "middle";  
  6.    
  7.    for (var n = 0; n < this.numYTicks; n++)  
  8.     {  
  9.        var value = Math.round(this.maxY - n * this.maxY / this.numYTicks);  
  10.        context.save();  
  11.        context.translate(this.x - this.padding, n * this.height / this.numYTicks + this.y);  
  12.        context.fillText(value, 0, 0);  
  13.        context.restore();  
  14.     }  
  15.    context.restore();  
  16. }; 
Figure 5
 
This figure represents labels alongthe y axis as shown
 
y-axis1.jpg
 
Figure 6
 
This figure shows when the x-axis and y-axis are joined together
 
xy axis.jpg
Step 7
 
In the following step, we will draw the line. We will also describe the width and color of the line. Once the labels and lines are rendered, CanvasChart handles rendering the data points.
  1. LineChart.prototype.drawLine = function (data, color, width)  
  2. {  
  3.    var context = this.context;  
  4.    context.save();  
  5.    this.transformContext();  
  6.    context.lineWidth = width;  
  7.    context.strokeStyle = color;  
  8.    context.fillStyle = color;  
  9.    context.beginPath();  
  10.    context.moveTo(data[0].x * this.scaleX, data[0].y * this.scaleY);  
  11.    
  12.    for (var n = 0; n < data.length; n++)  
  13.      {  
  14.        var point = data[n];  
  15.    
  16.        // draw segment  
  17.        context.lineTo(point.x * this.scaleX, point.y * this.scaleY);  
  18.        context.stroke();  
  19.        context.closePath();  
  20.        context.beginPath();  
  21.        context.arc(point.x * this.scaleX, point.y * this.scaleY, this.pointRadius, 0, 2 * Math.PI, false);  
  22.        context.fill();  
  23.        context.closePath();  
  24.    
  25.        // position for next segment  
  26.        context.beginPath();  
  27.        context.moveTo(point.x * this.scaleX, point.y * this.scaleY);  
  28.      }  
  29.    context.restore();  
  30. };   
Step 8
 
In the following step, we will transform the context and move the context to the center.
  1. LineChart.prototype.transformContext = function ()  
  2. {  
  3.    var context = this.context;  
  4.    
  5.    // move context to center of canvas  
  6.    this.context.translate(this.x, this.y + this.height);  
  7.    
  8.    // invert the y scale so that that increments  
  9.    // as you move upwards  
  10.    context.scale(1, -1);  
  11. }; 
Step 9
 
In the following step, window onload we will call the "drawline()" method that will draw a line based on the following points that are placed on the graph.
  1. window.onload = function ()  
  2. {  
  3.    var myLineChart = new LineChart({  
  4.        canvasId: "myCanvas",  
  5.        minX: 0,  
  6.        minY: 0,  
  7.        maxX: 140,  
  8.        maxY: 100,  
  9.        unitsPerTickX: 10,  
  10.        unitsPerTickY: 10  
  11.    });  
  12.    
  13.   var data = [{  
  14.       x: 0,  
  15.       y: 0  
  16.    }, {  
  17.       x: 20,  
  18.       y: 10  
  19.    }, {  
  20.       x: 40,  
  21.       y: 15  
  22.    }, {  
  23.       x: 60,  
  24.       y: 40  
  25.    }, {  
  26.       x: 80,  
  27.       y: 60  
  28.    }, {  
  29.       x: 100,  
  30.       y: 50  
  31.    }, {  
  32.       x: 120,  
  33.       y: 85  
  34.    }, {  
  35.       x: 140,  
  36.       y: 100  
  37.   }];  
  38.    
  39.   myLineChart.drawLine(data, "blue", 3);  
  40.    
  41.   var data = [{  
  42.       x: 20,  
  43.       y: 85  
  44.    }, {  
  45.       x: 40,  
  46.       y: 75  
  47.    }, {  
  48.       x: 60,  
  49.       y: 75  
  50.    }, {  
  51.       x: 80,  
  52.       y: 45  
  53.    }, {  
  54.       x: 100,  
  55.       y: 65  
  56.    }, {  
  57.       x: 120,  
  58.       y: 40  
  59.    }, {  
  60.       x: 140,  
  61.       y: 35  
  62.   }];  
  63.    
  64.   myLineChart.drawLine(data, "red", 3);  
  65. }; 
Example
  1. <!DOCTYPE html>  
  2.    
  3. <html lang="en" xmlns="http://www.w3.org/1999/xhtml">  
  4. <head>  
  5.     <meta charset="utf-8" />  
  6.     <title>Line Chart in HTML5</title>  
  7.     <script>  
  8.         function LineChart(con) {  
  9.             // user defined properties  
  10.             this.canvas = document.getElementById(con.canvasId);  
  11.             this.minX = con.minX;  
  12.             this.minY = con.minY;  
  13.             this.maxX = con.maxX;  
  14.             this.maxY = con.maxY;  
  15.             this.unitsPerTickX = con.unitsPerTickX;  
  16.             this.unitsPerTickY = con.unitsPerTickY;  
  17.    
  18.             // constants  
  19.             this.padding = 10;  
  20.             this.tickSize = 10;  
  21.             this.axisColor = "#555";  
  22.             this.pointRadius = 5;  
  23.             this.font = "12pt Calibri";  
  24.    
  25.             this.fontHeight = 12;  
  26.    
  27.             // relationships       
  28.             this.context = this.canvas.getContext("2d");  
  29.             this.rangeX = this.maxX - this.minY;  
  30.             this.rangeY = this.maxY - this.minY;  
  31.             this.numXTicks = Math.round(this.rangeX / this.unitsPerTickX);  
  32.             this.numYTicks = Math.round(this.rangeY / this.unitsPerTickY);  
  33.             this.x = this.getLongestValueWidth() + this.padding * 2;  
  34.             this.y = this.padding * 2;  
  35.             this.width = this.canvas.width - this.x - this.padding * 2;  
  36.             this.height = this.canvas.height - this.y - this.padding - this.fontHeight;  
  37.             this.scaleX = this.width / this.rangeX;  
  38.             this.scaleY = this.height / this.rangeY;  
  39.    
  40.             // draw x y axis and tick marks  
  41.             this.drawXAxis();  
  42.             this.drawYAxis();  
  43.         }  
  44.    
  45.         LineChart.prototype.getLongestValueWidth = function () {  
  46.             this.context.font = this.font;  
  47.             var longestValueWidth = 0;  
  48.             for (var n = 0; n <= this.numYTicks; n++) {  
  49.                 var value = this.maxY - (n * this.unitsPerTickY);  
  50.                 longestValueWidth = Math.max(longestValueWidth, this.context.measureText(value).width);  
  51.             }  
  52.             return longestValueWidth;  
  53.         };  
  54.    
  55.         LineChart.prototype.drawXAxis = function () {  
  56.             var context = this.context;  
  57.             context.save();  
  58.             context.beginPath();  
  59.             context.moveTo(this.x, this.y + this.height);  
  60.             context.lineTo(this.x + this.width, this.y + this.height);  
  61.             context.strokeStyle = this.axisColor;  
  62.             context.lineWidth = 2;  
  63.             context.stroke();  
  64.    
  65.             // draw tick marks  
  66.             for (var n = 0; n < this.numXTicks; n++) {  
  67.                 context.beginPath();  
  68.                 context.moveTo((n + 1) * this.width / this.numXTicks + this.x, this.y + this.height);  
  69.                 context.lineTo((n + 1) * this.width / this.numXTicks + this.x, this.y + this.height - this.tickSize);  
  70.                 context.stroke();  
  71.             }  
  72.    
  73.             // draw labels  
  74.             context.font = this.font;  
  75.             context.fillStyle = "black";  
  76.             context.textAlign = "center";  
  77.             context.textBaseline = "middle";  
  78.    
  79.             for (var n = 0; n < this.numXTicks; n++) {  
  80.                 var label = Math.round((n + 1) * this.maxX / this.numXTicks);  
  81.                 context.save();  
  82.                 context.translate((n + 1) * this.width / this.numXTicks + this.x, this.y + this.height + this.padding);  
  83.                 context.fillText(label, 0, 0);  
  84.                 context.restore();  
  85.             }  
  86.             context.restore();  
  87.         };  
  88.    
  89.         LineChart.prototype.drawYAxis = function () {  
  90.             var context = this.context;  
  91.             context.save();  
  92.             context.save();  
  93.             context.beginPath();  
  94.             context.moveTo(this.x, this.y);  
  95.             context.lineTo(this.x, this.y + this.height);  
  96.             context.strokeStyle = this.axisColor;  
  97.             context.lineWidth = 2;  
  98.             context.stroke();  
  99.             context.restore();  
  100.    
  101.             // draw tick marks  
  102.             for (var n = 0; n < this.numYTicks; n++) {  
  103.                 context.beginPath();  
  104.                 context.moveTo(this.x, n * this.height / this.numYTicks + this.y);  
  105.                 context.lineTo(this.x + this.tickSize, n * this.height / this.numYTicks + this.y);  
  106.                 context.stroke();  
  107.             }  
  108.    
  109.             // draw values  
  110.             context.font = this.font;  
  111.             context.fillStyle = "black";  
  112.             context.textAlign = "right";  
  113.             context.textBaseline = "middle";  
  114.    
  115.             for (var n = 0; n < this.numYTicks; n++) {  
  116.                 var value = Math.round(this.maxY - n * this.maxY / this.numYTicks);  
  117.                 context.save();  
  118.                 context.translate(this.x - this.padding, n * this.height / this.numYTicks + this.y);  
  119.                 context.fillText(value, 0, 0);  
  120.                 context.restore();  
  121.             }  
  122.             context.restore();  
  123.         };  
  124.    
  125.         LineChart.prototype.drawLine = function (data, color, width) {  
  126.             var context = this.context;  
  127.             context.save();  
  128.             this.transformContext();  
  129.             context.lineWidth = width;  
  130.             context.strokeStyle = color;  
  131.             context.fillStyle = color;  
  132.             context.beginPath();  
  133.             context.moveTo(data[0].x * this.scaleX, data[0].y * this.scaleY);  
  134.    
  135.             for (var n = 0; n < data.length; n++) {  
  136.                 var point = data[n];  
  137.    
  138.                 // draw segment  
  139.                 context.lineTo(point.x * this.scaleX, point.y * this.scaleY);  
  140.                 context.stroke();  
  141.                 context.closePath();  
  142.                 context.beginPath();  
  143.                 context.arc(point.x * this.scaleX, point.y * this.scaleY, this.pointRadius, 0, 2 * Math.PI, false);  
  144.                 context.fill();  
  145.                 context.closePath();  
  146.    
  147.                 // position for next segment  
  148.                 context.beginPath();  
  149.                 context.moveTo(point.x * this.scaleX, point.y * this.scaleY);  
  150.             }  
  151.             context.restore();  
  152.         };  
  153.    
  154.         LineChart.prototype.transformContext = function () {  
  155.             var context = this.context;  
  156.    
  157.             // move context to center of canvas  
  158.             this.context.translate(this.x, this.y + this.height);  
  159.    
  160.             // invert the y scale so that that increments  
  161.             // as you move upwards  
  162.             context.scale(1, -1);  
  163.         };  
  164.    
  165.         window.onload = function () {  
  166.             var myLineChart = new LineChart({  
  167.                 canvasId: "myCanvas",  
  168.                 minX: 0,  
  169.                 minY: 0,  
  170.                 maxX: 140,  
  171.                 maxY: 100,  
  172.                 unitsPerTickX: 10,  
  173.                 unitsPerTickY: 10  
  174.             });  
  175.    
  176.             var data = [{  
  177.                 x: 0,  
  178.                 y: 0  
  179.             }, {  
  180.                 x: 20,  
  181.                 y: 10  
  182.             }, {  
  183.                 x: 40,  
  184.                 y: 15  
  185.             }, {  
  186.                 x: 60,  
  187.                 y: 40  
  188.             }, {  
  189.                 x: 80,  
  190.                 y: 60  
  191.             }, {  
  192.                 x: 100,  
  193.                 y: 50  
  194.             }, {  
  195.                 x: 120,  
  196.                 y: 85  
  197.             }, {  
  198.                 x: 140,  
  199.                 y: 100  
  200.             }];  
  201.    
  202.             myLineChart.drawLine(data, "blue", 3);  
  203.    
  204.             var data = [{  
  205.                 x: 20,  
  206.                 y: 85  
  207.             }, {  
  208.                 x: 40,  
  209.                 y: 75  
  210.             }, {  
  211.                 x: 60,  
  212.                 y: 75  
  213.             }, {  
  214.                 x: 80,  
  215.                 y: 45  
  216.             }, {  
  217.                 x: 100,  
  218.                 y: 65  
  219.             }, {  
  220.                 x: 120,  
  221.                 y: 40  
  222.             }, {  
  223.                 x: 140,  
  224.                 y: 35  
  225.             }];  
  226.    
  227.             myLineChart.drawLine(data, "red", 3);  
  228.         };  
  229.     </script>  
  230. </head>  
  231. <body>  
  232.     <canvas id="myCanvas" width="600" height="300" style="border: 1px solid black;"></canvas>  
  233. </body>  
  234. </html> 
Output
 
linegraphxy.jpg

Similar Articles