{"id":16946,"date":"2017-05-01T16:15:13","date_gmt":"2017-05-01T13:15:13","guid":{"rendered":"http:\/\/www.webcodegeeks.com\/?p=16946"},"modified":"2017-12-19T13:01:31","modified_gmt":"2017-12-19T11:01:31","slug":"html5-graphs-tutorial","status":"publish","type":"post","link":"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/","title":{"rendered":"HTML5 Graphs Tutorial"},"content":{"rendered":"<p>One of the most expected features of HTML5 was the introduction of the canvas element, allowing to draw graphics on it. This tutorial will show how to draw graphs on it, starting from the lowest level, and ending with a JavaScript library.<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n[ulp id=&#8217;tgm4cmEWcKUikZNn&#8217;]<br \/>\n&nbsp;<br \/>\nAs it is an HTML example, we won\u2019t need any web server or back-end language installed in our machine, just a web browser.<\/p>\n<p>For this example, the following browsers have been used for testing:<\/p>\n<ul>\n<li>Chromium\u00a056.0.2924.76.<\/li>\n<li>Firefox 52.0.1.<\/li>\n<li>Opera 44.0.<\/li>\n<\/ul>\n<div class=\"toc\">\n<h3>Table Of Contents<\/h3>\n<dl>\n<dt><a href=\"#section_1\">1. The canvas element<\/a><\/dt>\n<dt><a href=\"#section_2\">2. Drawing (more complex) graphics<\/a><\/dt>\n<dt><a href=\"#section_3\">3. Chart.js<\/a><\/dt>\n<dd><a href=\"#section_3_1\">3.1. Line chart<\/a><\/dd>\n<dd><a href=\"#section_3_2\">3.2. Bar chart<\/a><\/dd>\n<dd><a href=\"#section_3_3\">3.3. Pie chart<\/a><\/dd>\n<dt><a href=\"#section_4\">4. Summary<\/a><\/dt>\n<dt><a href=\"#section_5\">5. Download the source code<\/a><\/dt>\n<\/dl>\n<\/div>\n<h2 id=\"section_1\">1. The canvas element<\/h2>\n<p>The canvas element was one of the most expected novelties of HTML5. This element allows us to draw dynamically images in a webpage, usually done with JavaScript in combination with the canvas API.<\/p>\n<p>As said, the element we have to use is <code>canvas<\/code>. So, something like the following would be enough to start:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>canvas.html<\/em><\/span><\/p>\n<pre class=\"brush:html;highlight:[21]\">&lt;html&gt;\r\n&lt;head&gt;\r\n    &lt;meta charset=\"utf-8\"&gt;\r\n    &lt;title&gt;Graph - Canvas&lt;\/title&gt;\r\n    &lt;script src=\"canvas.js\"&gt;&lt;\/script&gt;\r\n    &lt;style&gt;\r\n        #wrapper {\r\n            width: 80%;\r\n            margin: 0 auto;\r\n            text-align: center;\r\n        }\r\n        #canvas {\r\n            border: 1px solid black;\r\n        }\r\n    &lt;\/style&gt;\r\n&lt;\/head&gt;\r\n\r\n&lt;body&gt;\r\n    &lt;div id=\"wrapper\"&gt;\r\n        &lt;h1&gt;HTML5 Canvas&lt;\/h1&gt;\r\n        &lt;canvas id=\"canvas\" width=\"400\" height=\"400\"&gt;&lt;\/canvas&gt;\r\n    &lt;\/div&gt;\r\n&lt;\/body&gt;\r\n&lt;\/html&gt;\r\n<\/pre>\n<p>This will render a white canvas in the browser of 400&#215;400\u00a0(with the black border set with the CSS). Nothing very exciting.<\/p>\n<p>But, now that we have our canvas, we can\u00a0<strong>draw<\/strong> on it. Let\u2019s see how to draw\u00a0a line to see the most elemental canvas functions.<\/p>\n<p><em><span style=\"text-decoration: underline;\">canvas.js<\/span><\/em><\/p>\n<pre class=\"brush:javascript\">document.addEventListener('DOMContentLoaded', function(event) {\r\n    var canvas = document.getElementById('canvas'),\r\n    context = canvas.getContext('2d');\r\n\r\n    context.beginPath();\r\n    context.moveTo(0, 0);\r\n    context.lineTo(400, 400);\r\n    context.strokeStyle = '#7142f4';\r\n    context.stroke();\r\n});\r\n<\/pre>\n<p>The first thing we do is to bind the piece of code that manipulates the canvas to the <code>DOMContentLoaded<\/code> listener, since we have to be sure that the elements are loaded before we access them.<\/p>\n<p>Then, we get the canvas object from the DOM. But, for drawing on it, we need to get the render context of the canvas, the 2D context. This context offers the method for drawing in the canvas.<\/p>\n<p>For drawing a line, the first thing we do is calling <code>beginPath()<\/code> method. This is for telling to the canvas that, effectively, what we are going to do is to draw a path (line).<\/p>\n<p>Then, we have to set the beginning of the path in the coordinate system, with <code>moveTo()<\/code> method. We have to take into account that, in the pixel coordinate system, the (0, 0) is placed in the top-left corner, that is, the Y axis is inverted in regard to the cartesian coordinate system. So, the path will begin in the top-left corner of the canvas.<\/p>\n<p>We can also set the style of the line, assigning a color to the <code>strokeStyle<\/code> property of the context object. The default color is black.<\/p>\n<p>Finally, to draw the line for the defined path, we have to call the <code>stroke()<\/code> method. This is what we would see in the browser:<\/p>\n<figure style=\"width: 469px\" class=\"wp-caption aligncenter\"><img decoding=\"async\" src=\"http:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/04\/canvas_path.jpg\" alt=\"1. Drawing a line on a canvas.\" width=\"469\" height=\"574\" \/><figcaption class=\"wp-caption-text\">1. Drawing a line on a canvas.<\/figcaption><\/figure>\n<h2 id=\"section_2\">2. Drawing (more complex) graphics<\/h2>\n<p>Actually, we can consider a graphic what we have done above. But let&#8217;s see a more thorough example.<\/p>\n<p>Let&#8217;s suppose that we want to want to show a graphic of the world&#8217;s population growth, per continent. We can use the following dataset for this:<\/p>\n<table class=\"demo\">\n<caption>\u00a0<\/caption>\n<thead>\n<tr>\n<th><strong>Continent<\/strong><\/th>\n<th><strong>1700<\/strong><\/th>\n<th><strong>1750<\/strong><\/th>\n<th><strong>1800<\/strong><\/th>\n<th><strong>1850<\/strong><\/th>\n<th><strong>1900<\/strong><\/th>\n<th><strong>1950<\/strong><\/th>\n<th><strong>2000<\/strong><\/th>\n<th><strong>2050<\/strong><\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Africa<\/td>\n<td>106<\/td>\n<td>106<\/td>\n<td>107<\/td>\n<td>111<\/td>\n<td>133<\/td>\n<td>221<\/td>\n<td>783<\/td>\n<td>2478<\/td>\n<\/tr>\n<tr>\n<td>America<\/td>\n<td>12<\/td>\n<td>18<\/td>\n<td>31<\/td>\n<td>64<\/td>\n<td>156<\/td>\n<td>339<\/td>\n<td>820<\/td>\n<td>1217<\/td>\n<\/tr>\n<tr>\n<td>Asia<\/td>\n<td>441<\/td>\n<td>502<\/td>\n<td>635<\/td>\n<td>809<\/td>\n<td>947<\/td>\n<td>1402<\/td>\n<td>3700<\/td>\n<td>5267<\/td>\n<\/tr>\n<tr>\n<td>Europe<\/td>\n<td>178<\/td>\n<td>190<\/td>\n<td>203<\/td>\n<td>276<\/td>\n<td>408<\/td>\n<td>547<\/td>\n<td>675<\/td>\n<td>734<\/td>\n<\/tr>\n<tr>\n<td>Oceania<\/td>\n<td>3<\/td>\n<td>2<\/td>\n<td>2<\/td>\n<td>2<\/td>\n<td>6<\/td>\n<td>13<\/td>\n<td>30<\/td>\n<td>57<\/td>\n<\/tr>\n<tr>\n<td>World<\/td>\n<td>710<\/td>\n<td>791<\/td>\n<td>978<\/td>\n<td>1262<\/td>\n<td>1650<\/td>\n<td>2521<\/td>\n<td>6008<\/td>\n<td>9725<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>(Souce: Wikipedia)<\/p>\n<p>Note: the values for the year 2050 are, obviously, an estimation. But this is not important for our purposes.<\/p>\n<p>For this, we will use almost the same HTML base:<\/p>\n<p><em><span style=\"text-decoration: underline;\">canvas_population.html<\/span><\/em><\/p>\n<pre class=\"&quot;brush:html\">&lt;html&gt;\r\n&lt;head&gt;\r\n    &lt;meta charset=\"utf-8\"&gt;\r\n    &lt;title&gt;Graph - Canvas&lt;\/title&gt;\r\n    &lt;script src=\"canvas.js\"&gt;&lt;\/script&gt;\r\n    &lt;style&gt;\r\n        #wrapper {\r\n            width: 80%;\r\n            margin: 0 auto;\r\n            text-align: center;\r\n        }\r\n    &lt;\/style&gt;\r\n&lt;\/head&gt;\r\n\r\n&lt;body&gt;\r\n    &lt;div id=\"wrapper\"&gt;\r\n        &lt;h1&gt;World population growth&lt;\/h1&gt;\r\n        &lt;canvas id=\"canvas\" height=\"400\" width=\"650\"&gt;&lt;\/canvas&gt;\r\n    &lt;\/div&gt;\r\n&lt;\/body&gt;\r\n&lt;\/html&gt;<\/pre>\n<p>The JavaScript would be the following:<\/p>\n<p><em><span style=\"text-decoration: underline;\">canvas_population.js<\/span><\/em><\/p>\n<pre class=\"brush:javascript;highlight:[10,29,30]\">var populationGrowth = {\r\n    'africa' : [106, 106, 107, 111, 133, 221, 783, 2478],\r\n    'america': [12, 18, 31, 64, 156, 339, 820, 1217],\r\n    'asia' : [411, 502, 635, 809, 947, 1402, 3700, 5267],\r\n    'europe' : [178, 190, 203, 276, 408, 547, 675, 734],\r\n    'oceania': [3, 2, 2, 2, 6, 13, 30, 57],\r\n    'world' : [710, 791, 978, 1262, 1650, 2521, 6008, 9725]\r\n};\r\n\r\nvar xScale = 50;\r\n\r\nfunction initCanvas() {\r\n    var canvas = document.getElementById('canvas'),\r\n        context = canvas.getContext(\"2d\");\r\n\r\n    context.strokeColor = '#7142f4';\r\n\r\n    return context;\r\n}\r\n\r\nfunction plotDataset(context, dataSet) {\r\n    var canvasHeight = context.canvas.height;\r\n\r\n    context.beginPath();\r\n    context.moveTo(0, dataSet[0]);\r\n\r\n    for (var populationIndex = 0; populationIndex &lt; dataSet.length; populationIndex++) {\r\n        var population = dataSet[populationIndex],\r\n            xCoordinate = populationIndex * xScale,\r\n            yCoordinate = canvasHeight - population;\r\n\r\n        context.lineTo(xCoordinate, yCoordinate);\r\n    }\r\n\r\n    context.stroke();\r\n}\r\n\r\nfunction draw(context, dataSet) {\r\n    for (var continent in dataSet) {\r\n        var population = dataSet[continent];\r\n\r\n        plotDataset(context, population);\r\n    }\r\n}\r\n\r\ndocument.addEventListener('DOMContentLoaded', function(event) {\r\n    var context = initCanvas();\r\n\r\n    draw(context, populationGrowth);\r\n});\r\n<\/pre>\n<p>Let&#8217;s examine the code:<\/p>\n<p>The first thing we do is to define an object with our data. Nothing very special.<\/p>\n<p>Then, we define, in line 10, a scaling value for the X axis. This is for defining the &#8220;distance&#8221; between each value in the X axis. As you can see, this is a complete arbitrary value. We will leave as it is for the moment.<\/p>\n<p>The function for initializing the canvas doesn&#8217;t do anything we don&#8217;t know already.<\/p>\n<p>The one for plotting the dataset (the dataset will be the array of values for each continent) is the most interesting one. Note that the first thing we do is to save the height of the canvas. After beginning the path and moving the initial point (which is the (0, &lt;first-value&gt;)) for the dataset in question, we start looping each value of the dataset. For the X coordinate, we multiply the value itself with the scaling value, as explained above. And, for the Y coordinate, we have to &#8220;invert&#8221; the actual value because, remember, the Y axis in the pixel coordinate system goes &#8220;top-down&#8221;. To display the actual value in the system, we just have to subtract the value in question to the canvas height.<\/p>\n<p>The last function is just for iterating the object with the datasets and calling to the method described in the paragraph above.<\/p>\n<p>Finally, when the DOM is loaded, we just init the context, and draw the data.<\/p>\n<p>The result will be the following:<\/p>\n<figure style=\"width: 695px\" class=\"wp-caption aligncenter\"><img decoding=\"async\" src=\"http:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/04\/canvas_population_growth.jpg\" alt=\"2. Displaying datasets on a canvas.\" width=\"695\" height=\"562\" \/><figcaption class=\"wp-caption-text\">2. Displaying datasets on a canvas.<\/figcaption><\/figure>\n<p>Perhaps results quite disappointing. Apart from the frankly improvable style, not even all the datasets are displayed. And, for those being displayed, not all the data is shown.<\/p>\n<p>Instead of investing our time and efforts in drawing ugly charts, we will see how to draw stunning charts with a JavaScript library.<\/p>\n<h2 id=\"section_3\">3. Chart.js<\/h2>\n<p>We have already seen how to draw a graphic natively, defining several datasets and building our own functions to draw the data in the canvas. But the functions we have coded are just applicable for a specific kind of graphic, a line chart. At the moment we would need to display another kind of graphic, we would have to build the functions from the scratch.<\/p>\n<p>Fortunately, there&#8217;s available a library for drawing beautiful charts, with a very huge variety, named Chart.js. In this section, we will see how to draw several types of graphics with this library.<\/p>\n<p>For using it, we can load it from a CDN, or download it to our workspace. It&#8217;s available in <a href=\"https:\/\/cdnjs.com\/libraries\/Chart.js\">cdnjs.com<\/a>. In this tutorial, we have used the version 2.5.0.<\/p>\n<h3 id=\"section_3_1\">3.1. Line chart<\/h3>\n<p>The best way to begin using Chart.js is using the same chart type we have build manually.<\/p>\n<p>The base HTML will be almost the same, as usual:<\/p>\n<p><em><span style=\"text-decoration: underline;\">chartjs_line.html<\/span><\/em><\/p>\n<pre class=\"brush:html\">&lt;!DOCTYPE html&gt;\r\n&lt;html&gt;\r\n&lt;head&gt;\r\n    &lt;meta charset=\"utf-8\"&gt;\r\n    &lt;title&gt;Chart.js - Line chart&lt;\/title&gt;\r\n    &lt;script src=\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/Chart.js\/2.5.0\/Chart.bundle.min.js\"&gt;&lt;\/script&gt;\r\n    &lt;script src=\"line.js\"&gt;&lt;\/script&gt;\r\n    &lt;style&gt;\r\n        #wrapper {\r\n            width: 60%;\r\n            margin: 0 auto;\r\n            text-align: center;\r\n        }\r\n    &lt;\/style&gt;\r\n\r\n&lt;\/head&gt;\r\n&lt;body&gt;\r\n    &lt;div id=\"wrapper\"&gt;\r\n        &lt;h1&gt;Chart.js - Population growth&lt;\/h1&gt;\r\n        &lt;canvas id=\"canvas\" width=\"400\" height=\"200\" &gt;&lt;\/canvas&gt;\r\n    &lt;\/div&gt;\r\n&lt;\/body&gt;\r\n&lt;\/html&gt;\r\n<\/pre>\n<p>The JavaScript will be the following:<\/p>\n<p><em><span style=\"text-decoration: underline;\">chartjs_line.js<\/span><\/em><\/p>\n<pre class=\"brush:javascript\">var years = [1700, 1750, 1800, 1850, 1900, 1950, 2000, 2050];\r\n\r\nvar population = {\r\n    labels: years,\r\n    datasets: [\r\n        {\r\n            label: 'Africa',\r\n            borderColor: \"rgba(220,180,0,1)\",\r\n            pointColor: \"rgba(220,180,0,1)\",\r\n            lineTension: 0,\r\n            fill: false,\r\n            data: [106, 106, 107, 111, 133, 221, 783, 2478]\r\n        }, {\r\n            label: 'America',\r\n            borderColor: \"rgba(94,5,115,1)\",\r\n            pointColor: \"rgba(151,187,205,1)\",\r\n            lineTension: 0,\r\n            fill: false,\r\n            data: [12, 18, 31, 64, 156, 339, 820, 1217]\r\n        }, {\r\n            label: 'Asia',\r\n            borderColor: \"rgba(151,187,205,1)\",\r\n            pointColor: \"rgba(151,187,205,1)\",\r\n            lineTension: 0,\r\n            fill: false,\r\n            data: [411, 502, 635, 809, 947, 1402, 3700, 5267]\r\n        }, {\r\n            label: 'Europe',\r\n            borderColor: \"rgba(46,103,219,1)\",\r\n            pointColor: \"rgba(151,187,205,1)\",\r\n            lineTension: 0,\r\n            fill: false,\r\n            data: [178, 190, 203, 276, 408, 547, 675, 734]\r\n        }, {\r\n            label: 'Oceania',\r\n            borderColor: \"rgba(189,50,189 ,1)\",\r\n            pointColor: \"rgba(151,187,205,1)\",\r\n            lineTension: 0,\r\n            fill: false,\r\n            data: [3, 2, 2, 2, 6, 13, 30, 57]\r\n        }, {\r\n            label: 'World',\r\n            borderColor: \"rgb(3,202,103)\",\r\n            pointColor: \"rgba(3,202,103,1)\",\r\n            lineTension: 0,\r\n            fill: false,\r\n            data: [710, 791, 978, 1262, 1650, 2521, 6008, 9725]\r\n        },\r\n    ]\r\n};\r\n\r\n\r\ndocument.addEventListener('DOMContentLoaded', function(event) {\r\n    var context = document.getElementById('canvas').getContext('2d');\r\n    var populationChart = new Chart(\r\n        context,\r\n        {\r\n            type: 'line',\r\n            data: population,\r\n        }\r\n    ); \r\n});<\/pre>\n<p>That&#8217;s it. All we have to do is define an object, with that structure, and then instantiate a Chart.<\/p>\n<p>Setting the <code>lineTension<\/code> to 0 will make the graphic lines straight, otherwise, they will be curved; and we set the <code>fill<\/code> to <code>false<\/code> not to fill underneath, since in this graphic wouldn&#8217;t make much sense. Leaving it as default, would result on a different chart type, an\u00a0<strong>area chart<\/strong>.<\/p>\n<p>And, with this, the output would be the following:<\/p>\n<figure style=\"width: 821px\" class=\"wp-caption aligncenter\"><img decoding=\"async\" src=\"http:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/04\/chartjs_line.jpg\" alt=\"3. Data displayed in figure 2, but using Chart.js.\" width=\"821\" height=\"556\" \/><figcaption class=\"wp-caption-text\">3. Data displayed in figure 2, but using Chart.js.<\/figcaption><\/figure>\n<p>Beautiful! And without the need of coding any JavaScript, besides the data definition.<\/p>\n<p>But that&#8217;s not all. We can interact with the chart. For example, if we click the top labels, we can hide\/show them:<\/p>\n<figure style=\"width: 826px\" class=\"wp-caption aligncenter\"><img decoding=\"async\" src=\"http:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/04\/chartjs_line_labels.jpg\" alt=\"4. Same chart, but hiding some datasets.\" width=\"826\" height=\"562\" \/><figcaption class=\"wp-caption-text\">4. Same chart, but hiding some datasets.<\/figcaption><\/figure>\n<p>And, if we place the cursor on each of the value points of the graph, the exact value will be displayed.<\/p>\n<h3 id=\"section_3_2\">3.2. Bar chart<\/h3>\n<p>The bar charts are used for representing graphically a dataset of quantitative, or qualitative, discrete data. The X axis represents the different modalities or concepts, and the Y axis the frequency of each one.<\/p>\n<p>So, yes, a bar chart may also be used for displaying the population of different areas. But, in this case, will reduce the number of years to display the population of, to 2, not to have an excessively huge graphic.<\/p>\n<p>With this, the JavaScript would be the following:<\/p>\n<pre class=\"brush:javascript\">var population = {\r\n    labels: ['Africa', 'America', 'Asia', 'Europe', 'Oceania', 'World'],\r\n    datasets: [\r\n        {\r\n            label: '2000 year population',\r\n            data: [783, 820, 3700, 675, 30, 6008],\r\n            backgroundColor: [\r\n               'rgba(255, 99, 132, 0.5)',\r\n               'rgba(255, 99, 132, 0.5)',\r\n               'rgba(255, 99, 132, 0.5)',\r\n               'rgba(255, 99, 132, 0.5)',\r\n               'rgba(255, 99, 132, 0.5)',\r\n               'rgba(255, 99, 132, 0.5)',\r\n           ],\r\n           borderColor: [\r\n              'rgba(255,99,132,1)',\r\n              'rgba(255,99,132,1)',\r\n              'rgba(255,99,132,1)',\r\n              'rgba(255,99,132,1)',\r\n              'rgba(255,99,132,1)',\r\n              'rgba(255,99,132,1)',\r\n          ],\r\n      }, {\r\n          label: '2050 year population (estimation)',\r\n          data: [2478, 1217, 5267, 734, 57, 9725],\r\n          backgroundColor: [\r\n             'rgba(17,216,235, 0.5)',\r\n             'rgba(17,216,235, 0.5)',\r\n             'rgba(17,216,235, 0.5)',\r\n             'rgba(17,216,235, 0.5)',\r\n             'rgba(17,216,235, 0.5)',\r\n             'rgba(17,216,235, 0.5)',\r\n         ],\r\n         borderColor: [\r\n             'rgba(17,216,235,1)',\r\n             'rgba(17,216,235,1)',\r\n             'rgba(17,216,235,1)',\r\n             'rgba(17,216,235,1)',\r\n             'rgba(17,216,235,1)',\r\n             'rgba(17,216,235,1)',\r\n         ],\r\n      }\r\n   ]\r\n};\r\n\r\n\r\ndocument.addEventListener('DOMContentLoaded', function(event) {\r\n    var context = document.getElementById('canvas').getContext('2d');\r\n    var clientsChart = new Chart(\r\n        context, {\r\n           type: 'bar',\r\n           data: population\r\n       }\r\n    ); \r\n});<\/pre>\n<p>Note that, in this case, even if the data is the same, in the dataset has to be grouped by year, instead of by continent.<\/p>\n<p>For this, the rendered chart is this one:<\/p>\n<figure style=\"width: 801px\" class=\"wp-caption aligncenter\"><img decoding=\"async\" src=\"http:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/04\/bar2.jpg\" alt=\"5. Bar chart using Chart.js.\" width=\"801\" height=\"569\" \/><figcaption class=\"wp-caption-text\">5. Bar chart using Chart.js.<\/figcaption><\/figure>\n<h3 id=\"section_3_3\">3.3. Pie chart<\/h3>\n<p>The circular or &#8220;pie&#8221; chart is commonly used for displaying percentages and proportions.<\/p>\n<p>This means that our previous examples are not applicable for this type of chart, so we will have to change the data we are going to represent. For this case we could use, for instance, the area extension percentage of each continent (omitting the sea).<\/p>\n<p><em><span style=\"text-decoration: underline;\">chartjs_pie.js<\/span><\/em><\/p>\n<pre class=\"brush:javascript\">var continentsArea = {\r\n    labels: ['Asia', 'America', 'Africa', 'Europe', 'Antartica', 'Oceania'],\r\n    datasets: [\r\n    {\r\n        backgroundColor: [\r\n           'rgba(234,223,74, 0.5)',\r\n           'rgba(252,21,56 , 0.2)',\r\n           'rgba(211,213,232 , 0.2)',\r\n           'rgba(75, 192, 192, 0.2)',\r\n           'rgba(153, 102, 255, 0.2)',\r\n           'rgba(255, 159, 64, 0.2)'\r\n       ],\r\n       borderColor: [\r\n           'rgba(234,223,74, 0.8)',\r\n           'rgba(252,21,56 , 0.8)',\r\n           'rgba(211,213,232, 0.8)',\r\n           'rgba(83,210,189, 0.8)',\r\n           'rgba(153, 102, 255, 0.8)',\r\n           'rgba(255, 159, 64, 0.8)'\r\n       ],\r\n       data: [30, 28, 20, 7, 9, 6]\r\n     },\r\n   ]\r\n};\r\n\r\n\r\ndocument.addEventListener('DOMContentLoaded', function(event) {\r\n    var context = document.getElementById('continents').getContext('2d');\r\n    var continentsChart = new Chart(\r\n       context,\r\n       {\r\n           type: 'pie',\r\n           data: continentsArea\r\n       }\r\n    ); \r\n});<\/pre>\n<p>The output would be the following:<\/p>\n<figure style=\"width: 597px\" class=\"wp-caption aligncenter\"><img decoding=\"async\" src=\"http:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/04\/pie.jpg\" alt=\"6. Pie chart using Chart.js.\" width=\"597\" height=\"530\" \/><figcaption class=\"wp-caption-text\">6. Pie chart using Chart.js.<\/figcaption><\/figure>\n<p><strong>Note<\/strong>: for pie charts, we can also &#8220;nest&#8221; data. Applying it to the previous example of the population growth through the time, would consist on, first, assigning the population percentage to each continent per year; and then, display the data of several years. The resulting chart would be a pie of several circles, with the data of each year for each circle.<\/p>\n<p><strong>Note 2:<\/strong> if, instead of &#8220;pie&#8221;, we instantiate the chart as &#8220;doughnut&#8221;, we would have the same chart, but with a &#8220;donut&#8221; appearance.<\/p>\n<h2 id=\"section_4\">4. Summary<\/h2>\n<p>This tutorial has shown how to draw charts with HTML5, starting from the scratch with the key element for this, the canvas element. This element allows us to draw figures with JavaScript, being able to draw graphics form a dataset. But the effort it requires is pretty high for the results we would obtain. That&#8217;s why we have seen how to use the Chart.js library, the JavaScript library for drawing beautiful charts in an incredibly easy way. We have seen that, with this library, we can draw any of the most common graphics without programming, apart from, obviously, declaring the dataset objects.<\/p>\n<h2 id=\"section_5\">5. Download the source code<\/h2>\n<p>This was an example of HTML5 Graphs Tutorial.<\/p>\n<div class=\"download\"><strong>Download<\/strong><br \/>\nYou can download the full source code of this example here: <a href=\"http:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/04\/HTML5GraphsTutorial.zip\"><strong>HTML5GraphsTutorial<\/strong><\/a><\/div>\n","protected":false},"excerpt":{"rendered":"<p>One of the most expected features of HTML5 was the introduction of the canvas element, allowing to draw graphics on it. This tutorial will show how to draw graphs on it, starting from the lowest level, and ending with a JavaScript library. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [ulp id=&#8217;tgm4cmEWcKUikZNn&#8217;] &nbsp; As it &hellip;<\/p>\n","protected":false},"author":160,"featured_media":914,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[12],"tags":[],"class_list":["post-16946","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-html5"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>HTML5 Graphs Tutorial - Web Code Geeks - 2026<\/title>\n<meta name=\"description\" content=\"One of the most expected features of HTML5 was the introduction of the canvas element, allowing to draw graphics on it. This tutorial will show how to\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"HTML5 Graphs Tutorial - Web Code Geeks - 2026\" \/>\n<meta property=\"og:description\" content=\"One of the most expected features of HTML5 was the introduction of the canvas element, allowing to draw graphics on it. This tutorial will show how to\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/\" \/>\n<meta property=\"og:site_name\" content=\"Web Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/webcodegeeks\" \/>\n<meta property=\"article:published_time\" content=\"2017-05-01T13:15:13+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2017-12-19T11:01:31+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/html5-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Toni\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@webcodegeeks\" \/>\n<meta name=\"twitter:site\" content=\"@webcodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Toni\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"11 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/\"},\"author\":{\"name\":\"Toni\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/54a7be647b0b871cff41cbf3d2a95966\"},\"headline\":\"HTML5 Graphs Tutorial\",\"datePublished\":\"2017-05-01T13:15:13+00:00\",\"dateModified\":\"2017-12-19T11:01:31+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/\"},\"wordCount\":1617,\"commentCount\":1,\"publisher\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/html5-logo.jpg\",\"articleSection\":[\"HTML5\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/\",\"url\":\"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/\",\"name\":\"HTML5 Graphs Tutorial - Web Code Geeks - 2026\",\"isPartOf\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/html5-logo.jpg\",\"datePublished\":\"2017-05-01T13:15:13+00:00\",\"dateModified\":\"2017-12-19T11:01:31+00:00\",\"description\":\"One of the most expected features of HTML5 was the introduction of the canvas element, allowing to draw graphics on it. This tutorial will show how to\",\"breadcrumb\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/#primaryimage\",\"url\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/html5-logo.jpg\",\"contentUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/html5-logo.jpg\",\"width\":150,\"height\":150},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.webcodegeeks.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"HTML5\",\"item\":\"https:\/\/www.webcodegeeks.com\/category\/html5\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"HTML5 Graphs Tutorial\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#website\",\"url\":\"https:\/\/www.webcodegeeks.com\/\",\"name\":\"Web Code Geeks\",\"description\":\"Web Developers Resource Center\",\"publisher\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.webcodegeeks.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\/\/www.webcodegeeks.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"contentUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/webcodegeeks\",\"https:\/\/x.com\/webcodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/54a7be647b0b871cff41cbf3d2a95966\",\"name\":\"Toni\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/21c1661474c78b4757355b8beef9ab1d14f490ee3a3e67392f4e618d36643d4c?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/21c1661474c78b4757355b8beef9ab1d14f490ee3a3e67392f4e618d36643d4c?s=96&d=mm&r=g\",\"caption\":\"Toni\"},\"url\":\"https:\/\/www.webcodegeeks.com\/author\/julen-pardo\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"HTML5 Graphs Tutorial - Web Code Geeks - 2026","description":"One of the most expected features of HTML5 was the introduction of the canvas element, allowing to draw graphics on it. This tutorial will show how to","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/","og_locale":"en_US","og_type":"article","og_title":"HTML5 Graphs Tutorial - Web Code Geeks - 2026","og_description":"One of the most expected features of HTML5 was the introduction of the canvas element, allowing to draw graphics on it. This tutorial will show how to","og_url":"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/","og_site_name":"Web Code Geeks","article_publisher":"https:\/\/www.facebook.com\/webcodegeeks","article_published_time":"2017-05-01T13:15:13+00:00","article_modified_time":"2017-12-19T11:01:31+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/html5-logo.jpg","type":"image\/jpeg"}],"author":"Toni","twitter_card":"summary_large_image","twitter_creator":"@webcodegeeks","twitter_site":"@webcodegeeks","twitter_misc":{"Written by":"Toni","Est. reading time":"11 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/#article","isPartOf":{"@id":"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/"},"author":{"name":"Toni","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/54a7be647b0b871cff41cbf3d2a95966"},"headline":"HTML5 Graphs Tutorial","datePublished":"2017-05-01T13:15:13+00:00","dateModified":"2017-12-19T11:01:31+00:00","mainEntityOfPage":{"@id":"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/"},"wordCount":1617,"commentCount":1,"publisher":{"@id":"https:\/\/www.webcodegeeks.com\/#organization"},"image":{"@id":"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/#primaryimage"},"thumbnailUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/html5-logo.jpg","articleSection":["HTML5"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/","url":"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/","name":"HTML5 Graphs Tutorial - Web Code Geeks - 2026","isPartOf":{"@id":"https:\/\/www.webcodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/#primaryimage"},"image":{"@id":"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/#primaryimage"},"thumbnailUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/html5-logo.jpg","datePublished":"2017-05-01T13:15:13+00:00","dateModified":"2017-12-19T11:01:31+00:00","description":"One of the most expected features of HTML5 was the introduction of the canvas element, allowing to draw graphics on it. This tutorial will show how to","breadcrumb":{"@id":"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/#primaryimage","url":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/html5-logo.jpg","contentUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/html5-logo.jpg","width":150,"height":150},{"@type":"BreadcrumbList","@id":"https:\/\/www.webcodegeeks.com\/html5\/html5-graphs-tutorial\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.webcodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"HTML5","item":"https:\/\/www.webcodegeeks.com\/category\/html5\/"},{"@type":"ListItem","position":3,"name":"HTML5 Graphs Tutorial"}]},{"@type":"WebSite","@id":"https:\/\/www.webcodegeeks.com\/#website","url":"https:\/\/www.webcodegeeks.com\/","name":"Web Code Geeks","description":"Web Developers Resource Center","publisher":{"@id":"https:\/\/www.webcodegeeks.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.webcodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.webcodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/www.webcodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/webcodegeeks","https:\/\/x.com\/webcodegeeks"]},{"@type":"Person","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/54a7be647b0b871cff41cbf3d2a95966","name":"Toni","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/21c1661474c78b4757355b8beef9ab1d14f490ee3a3e67392f4e618d36643d4c?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/21c1661474c78b4757355b8beef9ab1d14f490ee3a3e67392f4e618d36643d4c?s=96&d=mm&r=g","caption":"Toni"},"url":"https:\/\/www.webcodegeeks.com\/author\/julen-pardo\/"}]}},"_links":{"self":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/posts\/16946","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/users\/160"}],"replies":[{"embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/comments?post=16946"}],"version-history":[{"count":0,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/posts\/16946\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/media\/914"}],"wp:attachment":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/media?parent=16946"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/categories?post=16946"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/tags?post=16946"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}