How to Draw a Line Graph Using Canvas in Html5

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. this .canvas = document.getElementById(con.canvasId);
  4. this .minX = con.minX;
  5. this .minY = con.minY;
  6. this .maxX = con.maxX;
  7. this .maxY = con.maxY;
  8. this .unitsPerTickX = con.unitsPerTickX;
  9. this .unitsPerTickY = con.unitsPerTickY;
  10. this .padding = 10;
  11. this .tickSize = 10;
  12. this .axisColor = "#555" ;
  13. this .pointRadius = 5;
  14. this .font = "12pt Calibri" ;
  15. this .fontHeight = 12;
  16. this .context = this .canvas.getContext( "2d" );
  17. this .rangeX = this .maxX - this .minY;
  18. this .rangeY = this .maxY - this .minY;
  19. this .numXTicks = Math.round( this .rangeX / this .unitsPerTickX);
  20. this .numYTicks = Math.round( this .rangeY / this .unitsPerTickY);
  21. this .x = this .getLongestValueWidth() + this .padding * 2;
  22. this .y = this .padding * 2;
  23. this .width = this .canvas.width - this .x - this .padding * 2;
  24. this .height = this .canvas.height - this .y - this .padding - this .fontHeight;
  25. this .scaleX = this .width / this .rangeX;
  26. this .scaleY = this .height / this .rangeY;
  27. this .drawXAxis();
  28. this .drawYAxis();
  29. }

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. for  ( var  n = 0; n < this .numXTicks; n++)
  12.     {
  13.        context.beginPath();
  14.        context.moveTo((n + 1) *this .width / this .numXTicks + this .x, this .y + this .height);
  15.        context.lineTo((n + 1) *this .width / this .numXTicks + this .x, this .y + this .height - this .tickSize);
  16.        context.stroke();
  17.     }

Figure 2

This figure represents tick mark along x-axis shown below

x axis.jpg

  1.    context.font =this .font;
  2.    context.fillStyle ="black" ;
  3.    context.textAlign ="center" ;
  4.    context.textBaseline ="middle" ;
  5. for  ( var  n = 0; n < this .numXTicks; n++)
  6.     {
  7. var  label = Math.round((n + 1) * this .maxX / this .numXTicks);
  8.        context.save();
  9.        context.translate((n + 1) *this .width / this .numXTicks + this .x, this .y + this .height + this .padding);
  10.        context.fillText(label, 0, 0);
  11.        context.restore();
  12.     }
  13.    context.restore();
  14. };

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. for  ( var  n = 0; n < this .numYTicks; n++)
  14.     {
  15.        context.beginPath();
  16.        context.moveTo(this .x, n * this .height / this .numYTicks + this .y);
  17.        context.lineTo(this .x + this .tickSize, n * this .height / this .numYTicks + this .y);
  18.        context.stroke();
  19.     }

Figure 4

This figure shows the tick mark along the y-axis:

y axis.jpg

  1.    context.font =this .font;
  2.    context.fillStyle ="black" ;
  3.    context.textAlign ="right" ;
  4.    context.textBaseline ="middle" ;
  5. for  ( var  n = 0; n < this .numYTicks; n++)
  6.     {
  7. var  value = Math.round( this .maxY - n * this .maxY / this .numYTicks);
  8.        context.save();
  9.        context.translate(this .x - this .padding, n * this .height / this .numYTicks + this .y);
  10.        context.fillText(value, 0, 0);
  11.        context.restore();
  12.     }
  13.    context.restore();
  14. };

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. for  ( var  n = 0; n < data.length; n++)
  12.      {
  13. var  point = data[n];
  14.        context.lineTo(point.x *this .scaleX, point.y * this .scaleY);
  15.        context.stroke();
  16.        context.closePath();
  17.        context.beginPath();
  18.        context.arc(point.x *this .scaleX, point.y * this .scaleY, this .pointRadius, 0, 2 * Math.PI, false );
  19.        context.fill();
  20.        context.closePath();
  21.        context.beginPath();
  22.        context.moveTo(point.x *this .scaleX, point.y * this .scaleY);
  23.      }
  24.    context.restore();
  25. };

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. this .context.translate( this .x, this .y + this .height);
  5.    context.scale(1, -1);
  6. };

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. var  data = [{
  13.       x: 0,
  14.       y: 0
  15.    }, {
  16.       x: 20,
  17.       y: 10
  18.    }, {
  19.       x: 40,
  20.       y: 15
  21.    }, {
  22.       x: 60,
  23.       y: 40
  24.    }, {
  25.       x: 80,
  26.       y: 60
  27.    }, {
  28.       x: 100,
  29.       y: 50
  30.    }, {
  31.       x: 120,
  32.       y: 85
  33.    }, {
  34.       x: 140,
  35.       y: 100
  36.   }];
  37.   myLineChart.drawLine(data,"blue" , 3);
  38. var  data = [{
  39.       x: 20,
  40.       y: 85
  41.    }, {
  42.       x: 40,
  43.       y: 75
  44.    }, {
  45.       x: 60,
  46.       y: 75
  47.    }, {
  48.       x: 80,
  49.       y: 45
  50.    }, {
  51.       x: 100,
  52.       y: 65
  53.    }, {
  54.       x: 120,
  55.       y: 40
  56.    }, {
  57.       x: 140,
  58.       y: 35
  59.   }];
  60.   myLineChart.drawLine(data,"red" , 3);
  61. };

Example

  1. <!DOCTYPE html>
  2. <html lang="en"  xmlns= "http://www.w3.org/1999/xhtml" >
  3. <head>
  4.     <meta charset="utf-8"  />
  5.     <title>Line Chartin  HTML5</title>
  6.     <script>
  7. function  LineChart(con) {
  8. this .canvas = document.getElementById(con.canvasId);
  9. this .minX = con.minX;
  10. this .minY = con.minY;
  11. this .maxX = con.maxX;
  12. this .maxY = con.maxY;
  13. this .unitsPerTickX = con.unitsPerTickX;
  14. this .unitsPerTickY = con.unitsPerTickY;
  15. this .padding = 10;
  16. this .tickSize = 10;
  17. this .axisColor = "#555" ;
  18. this .pointRadius = 5;
  19. this .font = "12pt Calibri" ;
  20. this .fontHeight = 12;
  21. this .context = this .canvas.getContext( "2d" );
  22. this .rangeX = this .maxX - this .minY;
  23. this .rangeY = this .maxY - this .minY;
  24. this .numXTicks = Math.round( this .rangeX / this .unitsPerTickX);
  25. this .numYTicks = Math.round( this .rangeY / this .unitsPerTickY);
  26. this .x = this .getLongestValueWidth() + this .padding * 2;
  27. this .y = this .padding * 2;
  28. this .width = this .canvas.width - this .x - this .padding * 2;
  29. this .height = this .canvas.height - this .y - this .padding - this .fontHeight;
  30. this .scaleX = this .width / this .rangeX;
  31. this .scaleY = this .height / this .rangeY;
  32. this .drawXAxis();
  33. this .drawYAxis();
  34.         }
  35.         LineChart.prototype.getLongestValueWidth =function  () {
  36. this .context.font = this .font;
  37. var  longestValueWidth = 0;
  38. for  ( var  n = 0; n <= this .numYTicks; n++) {
  39. var  value = this .maxY - (n * this .unitsPerTickY);
  40.                 longestValueWidth = Math.max(longestValueWidth,this .context.measureText(value).width);
  41.             }
  42. return  longestValueWidth;
  43.         };
  44.         LineChart.prototype.drawXAxis =function  () {
  45. var  context = this .context;
  46.             context.save();
  47.             context.beginPath();
  48.             context.moveTo(this .x, this .y + this .height);
  49.             context.lineTo(this .x + this .width, this .y + this .height);
  50.             context.strokeStyle =this .axisColor;
  51.             context.lineWidth = 2;
  52.             context.stroke();
  53. for  ( var  n = 0; n < this .numXTicks; n++) {
  54.                 context.beginPath();
  55.                 context.moveTo((n + 1) *this .width / this .numXTicks + this .x, this .y + this .height);
  56.                 context.lineTo((n + 1) *this .width / this .numXTicks + this .x, this .y + this .height - this .tickSize);
  57.                 context.stroke();
  58.             }
  59.             context.font =this .font;
  60.             context.fillStyle ="black" ;
  61.             context.textAlign ="center" ;
  62.             context.textBaseline ="middle" ;
  63. for  ( var  n = 0; n < this .numXTicks; n++) {
  64. var  label = Math.round((n + 1) * this .maxX / this .numXTicks);
  65.                 context.save();
  66.                 context.translate((n + 1) *this .width / this .numXTicks + this .x, this .y + this .height + this .padding);
  67.                 context.fillText(label, 0, 0);
  68.                 context.restore();
  69.             }
  70.             context.restore();
  71.         };
  72.         LineChart.prototype.drawYAxis =function  () {
  73. var  context = this .context;
  74.             context.save();
  75.             context.save();
  76.             context.beginPath();
  77.             context.moveTo(this .x, this .y);
  78.             context.lineTo(this .x, this .y + this .height);
  79.             context.strokeStyle =this .axisColor;
  80.             context.lineWidth = 2;
  81.             context.stroke();
  82.             context.restore();
  83. for  ( var  n = 0; n < this .numYTicks; n++) {
  84.                 context.beginPath();
  85.                 context.moveTo(this .x, n * this .height / this .numYTicks + this .y);
  86.                 context.lineTo(this .x + this .tickSize, n * this .height / this .numYTicks + this .y);
  87.                 context.stroke();
  88.             }
  89.             context.font =this .font;
  90.             context.fillStyle ="black" ;
  91.             context.textAlign ="right" ;
  92.             context.textBaseline ="middle" ;
  93. for  ( var  n = 0; n < this .numYTicks; n++) {
  94. var  value = Math.round( this .maxY - n * this .maxY / this .numYTicks);
  95.                 context.save();
  96.                 context.translate(this .x - this .padding, n * this .height / this .numYTicks + this .y);
  97.                 context.fillText(value, 0, 0);
  98.                 context.restore();
  99.             }
  100.             context.restore();
  101.         };
  102.         LineChart.prototype.drawLine =function  (data, color, width) {
  103. var  context = this .context;
  104.             context.save();
  105. this .transformContext();
  106.             context.lineWidth = width;
  107.             context.strokeStyle = color;
  108.             context.fillStyle = color;
  109.             context.beginPath();
  110.             context.moveTo(data[0].x *this .scaleX, data[0].y * this .scaleY);
  111. for  ( var  n = 0; n < data.length; n++) {
  112. var  point = data[n];
  113.                 context.lineTo(point.x *this .scaleX, point.y * this .scaleY);
  114.                 context.stroke();
  115.                 context.closePath();
  116.                 context.beginPath();
  117.                 context.arc(point.x *this .scaleX, point.y * this .scaleY, this .pointRadius, 0, 2 * Math.PI, false );
  118.                 context.fill();
  119.                 context.closePath();
  120.                 context.beginPath();
  121.                 context.moveTo(point.x *this .scaleX, point.y * this .scaleY);
  122.             }
  123.             context.restore();
  124.         };
  125.         LineChart.prototype.transformContext =function  () {
  126. var  context = this .context;
  127. this .context.translate( this .x, this .y + this .height);
  128.             context.scale(1, -1);
  129.         };
  130.         window.onload =function  () {
  131. var  myLineChart = new  LineChart({
  132.                 canvasId:"myCanvas" ,
  133.                 minX: 0,
  134.                 minY: 0,
  135.                 maxX: 140,
  136.                 maxY: 100,
  137.                 unitsPerTickX: 10,
  138.                 unitsPerTickY: 10
  139.             });
  140. var  data = [{
  141.                 x: 0,
  142.                 y: 0
  143.             }, {
  144.                 x: 20,
  145.                 y: 10
  146.             }, {
  147.                 x: 40,
  148.                 y: 15
  149.             }, {
  150.                 x: 60,
  151.                 y: 40
  152.             }, {
  153.                 x: 80,
  154.                 y: 60
  155.             }, {
  156.                 x: 100,
  157.                 y: 50
  158.             }, {
  159.                 x: 120,
  160.                 y: 85
  161.             }, {
  162.                 x: 140,
  163.                 y: 100
  164.             }];
  165.             myLineChart.drawLine(data,"blue" , 3);
  166. var  data = [{
  167.                 x: 20,
  168.                 y: 85
  169.             }, {
  170.                 x: 40,
  171.                 y: 75
  172.             }, {
  173.                 x: 60,
  174.                 y: 75
  175.             }, {
  176.                 x: 80,
  177.                 y: 45
  178.             }, {
  179.                 x: 100,
  180.                 y: 65
  181.             }, {
  182.                 x: 120,
  183.                 y: 40
  184.             }, {
  185.                 x: 140,
  186.                 y: 35
  187.             }];
  188.             myLineChart.drawLine(data,"red" , 3);
  189.         };
  190.     </script>
  191. </head>
  192. <body>
  193.     <canvas id="myCanvas"  width= "600"  height= "300"  style= "border: 1px solid black;" ></canvas>
  194. </body>
  195. </html>

Output

linegraphxy.jpg

How to Draw a Line Graph Using Canvas in Html5

Source: https://www.c-sharpcorner.com/UploadFile/18ddf7/html5-line-graph-using-canvas/

0 Response to "How to Draw a Line Graph Using Canvas in Html5"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel