In an earlier tutorial, we covered how to draw a pie chart or doughnut chart using HTML5 canvas. In this tutorial, I will show you how to use JavaScript and the HTML5 canvas to graphically display data by using bar charts. Show
What Is a Bar Chart?Bar charts are very common tools used to represent numerical data. From financial reports to PowerPoint presentations to infographics, bar charts are used very often since they offer a view of numerical data that is very easy to understand. Bar charts represent numerical data using bars, which are rectangles with either their widths or heights proportional to the numerical data that they represent. There are many types of bar charts, for example:
What Are the Components of a Bar Chart?Let's take a look at the components that make up a bar chart, regardless of its type:
Now that we know the components of a bar chart, let's see how we can write the JavaScript code to draw a chart like this. Drawing the Bar Chart Using JavaScriptSetting Up the JS ProjectTo start drawing using JavaScript and the HTML5 canvas, we will need to set up our project like this:
We'll keep things very simple and add the following code in index.html: <html> <body> <canvas id="myCanvas"></canvas> <script type="text/javascript" src="script.js"></script> </body> </html> We have the Add the following code in the script.js file: var myCanvas = document.getElementById("myCanvas"); myCanvas.width = 500; myCanvas.height = 500; var ctx = myCanvas.getContext("2d"); This gets a reference to the canvas element and then sets the width and height to Adding a Few Helper FunctionsDrawing the bar chart only requires knowing how to draw two elements:
Let's create the helper JS functions for these two elements. We will add the functions in our script.js file. function drawLine(ctx, startX, startY, endX, endY,color){ ctx.save(); ctx.strokeStyle = color; ctx.beginPath(); ctx.moveTo(startX,startY); ctx.lineTo(endX,endY); ctx.stroke(); ctx.restore(); } The
We are modifying the color settings for the We draw the line by calling Another helper function that we need is a function to draw a bar—which is a color-filled rectangle. Let's add it to script.js: function drawBar(ctx, upperLeftCornerX, upperLeftCornerY, width, height,color){ ctx.save(); ctx.fillStyle=color; ctx.fillRect(upperLeftCornerX,upperLeftCornerY,width,height); ctx.restore(); } The
The Bar Chart Data ModelNow that we have the helper functions in place, let's move on to the chart's data model. All types of chart, including bar charts, have a data model behind them. The data model is a structured set of numerical data. For this tutorial, we will use a data series of categories and their associated numerical values representing the number of vinyl records in my collection of records grouped by music genre:
We can represent this in JavaScript in the form of an object. We will pass this data to our
{ "Classical Music": 16, "Alternative Rock": 12, "Pop": 18, "Jazz": 32, } Implementing the BarChart ClassOur Implementing the Bar Chart ComponentLet's implement the class and methods that will do the actual drawing of our bar chart. We will do this by adding the following JavaScript code to our script.js file: class BarChart { constructor(options) { this.options = options; this.canvas = options.canvas; this.ctx = this.canvas.getContext("2d"); this.colors = options.colors; this.titleOptions = options.titleOptions; this.maxValue = Math.max(...Object.values(this.options.data)); } drawGridLines() { var canvasActualHeight = this.canvas.height - this.options.padding * 2; var canvasActualWidth = this.canvas.width - this.options.padding * 2; var gridValue = 0; while (gridValue <= this.maxValue) { var gridY = canvasActualHeight * (1 - gridValue / this.maxValue) + this.options.padding; drawLine( this.ctx, 0, gridY, this.canvas.width, gridY, this.options.gridColor ); drawLine( this.ctx, 15, this.options.padding/2, 15, gridY + this.options.padding/2, this.options.gridColor ); // Writing grid markers this.ctx.save(); this.ctx.fillStyle = this.options.gridColor; this.ctx.textBaseline = "bottom"; this.ctx.font = "bold 10px Arial"; this.ctx.fillText(gridValue, 0, gridY - 2); this.ctx.restore(); gridValue += this.options.gridScale; } } drawBars() { var canvasActualHeight = this.canvas.height - this.options.padding * 2; var canvasActualWidth = this.canvas.width - this.options.padding * 2; var barIndex = 0; var numberOfBars = Object.keys(this.options.data).length; var barSize = canvasActualWidth / numberOfBars; var values = Object.values(this.options.data); for (let val of values) { var barHeight = Math.round((canvasActualHeight * val) / this.maxValue); console.log(barHeight); drawBar( this.ctx, this.options.padding + barIndex * barSize, this.canvas.height - barHeight - this.options.padding, barSize, barHeight, this.colors[barIndex % this.colors.length] ); barIndex++; } } draw() { this.drawGridLines(); this.drawBars(); } } The class starts defining the constructor method to do some basic initialization by storing the Now, we will implement the The We then draw the grid lines of the chart. The To draw the grid lines, we use the helper function For every grid line, we also draw the value of the grid line 2 pixels above the grid line (that's why we have Next, we draw the bars by using the Using the Bar Chart ComponentLet's now see how to use the var myBarchart = new BarChart({ canvas: myCanvas, padding: 40, gridScale: 5, gridColor: "black", data: { "Classical Music": 16, "Alternative Rock": 12, "Pop": 18, "Jazz": 32, }, colors: ["#a55ca5", "#67b6c7", "#bccd7a", "#eb9743"], }); myBarchart.draw(); The code creates a new instance of the Adding the Data Series Name and Chart LegendTo add the data series name below the chart, we need to add the following method to our drawLabel() { this.ctx.save(); this.ctx.textBaseline = "bottom"; this.ctx.textAlign = this.titleOptions.align; this.ctx.fillStyle = this.titleOptions.fill; this.ctx.font = `${this.titleOptions.font.weight} ${this.titleOptions.font.size} ${this.titleOptions.font.family}`; let xPos = this.canvas.width / 2; if (this.titleOptions.align == "left") { xPos = 10; } if (this.titleOptions.align == "right") { xPos = this.canvas.width - 10; } this.ctx.fillText(this.options.seriesName, xPos, this.canvas.height); this.ctx.restore(); } We accept a bunch of font properties inside our Also update the draw() { this.drawGridLines(); this.drawBars(); this.drawLabel(); } We also need to change the way we instantiate the var myBarchart = new Barchart( { canvas:myCanvas, seriesName:"Vinyl records", padding:20, gridScale:5, gridColor:"#eeeeee", data: { "Classical Music": 16, "Alternative Rock": 12, "Pop": 18, "Jazz": 32, }, colors:["#a55ca5","#67b6c7", "#bccd7a","#eb9743"], titleOptions: { align: "center", fill: "black", font: { weight: "bold", size: "18px", family: "Lato" } } } ); myBarchart.draw(); And here is how the result looks: To add the legend, we first need to modify <html> <body> <canvas id="myCanvas" style="background: white;"></canvas> <legend for="myCanvas"></legend> <script type="text/javascript" src="script.js"></script> </body> </html> The var myCanvas = document.getElementById("myCanvas"); myCanvas.width = 500; myCanvas.height = 500; var ctx = myCanvas.getContext("2d"); function drawLine(ctx, startX, startY, endX, endY, color) { ctx.save(); ctx.strokeStyle = color; ctx.beginPath(); ctx.moveTo(startX, startY); ctx.lineTo(endX, endY); ctx.stroke(); ctx.restore(); } function drawBar( ctx, upperLeftCornerX, upperLeftCornerY, width, height, color ) { ctx.save(); ctx.fillStyle = color; ctx.fillRect(upperLeftCornerX, upperLeftCornerY, width, height); ctx.restore(); } class BarChart { constructor(options) { this.options = options; this.canvas = options.canvas; this.ctx = this.canvas.getContext("2d"); this.colors = options.colors; this.titleOptions = options.titleOptions; this.maxValue = Math.max(...Object.values(this.options.data)); } drawGridLines() { var canvasActualHeight = this.canvas.height - this.options.padding * 2; var canvasActualWidth = this.canvas.width - this.options.padding * 2; var gridValue = 0; while (gridValue <= this.maxValue) { var gridY = canvasActualHeight * (1 - gridValue / this.maxValue) + this.options.padding; drawLine( this.ctx, 0, gridY, this.canvas.width, gridY, this.options.gridColor ); drawLine( this.ctx, 15, this.options.padding / 2, 15, gridY + this.options.padding / 2, this.options.gridColor ); // Writing grid markers this.ctx.save(); this.ctx.fillStyle = this.options.gridColor; this.ctx.textBaseline = "bottom"; this.ctx.font = "bold 10px Arial"; this.ctx.fillText(gridValue, 0, gridY - 2); this.ctx.restore(); gridValue += this.options.gridStep; } } drawBars() { var canvasActualHeight = this.canvas.height - this.options.padding * 2; var canvasActualWidth = this.canvas.width - this.options.padding * 2; var barIndex = 0; var numberOfBars = Object.keys(this.options.data).length; var barSize = canvasActualWidth / numberOfBars; var values = Object.values(this.options.data); for (let val of values) { var barHeight = Math.round((canvasActualHeight * val) / this.maxValue); console.log(barHeight); drawBar( this.ctx, this.options.padding + barIndex * barSize, this.canvas.height - barHeight - this.options.padding, barSize, barHeight, this.colors[barIndex % this.colors.length] ); barIndex++; } } drawLabel() { this.ctx.save(); this.ctx.textBaseline = "bottom"; this.ctx.textAlign = this.titleOptions.align; this.ctx.fillStyle = this.titleOptions.fill; this.ctx.font = `${this.titleOptions.font.weight} ${this.titleOptions.font.size} ${this.titleOptions.font.family}`; let xPos = this.canvas.width / 2; if (this.titleOptions.align == "left") { xPos = 10; } if (this.titleOptions.align == "right") { xPos = this.canvas.width - 10; } this.ctx.fillText(this.options.seriesName, xPos, this.canvas.height); this.ctx.restore(); } drawLegend() { let pIndex = 0; let legend = document.querySelector("legend[for='myCanvas']"); let ul = document.createElement("ul"); legend.append(ul); for (let ctg of Object.keys(this.options.data)) { let li = document.createElement("li"); li.style.listStyle = "none"; li.style.borderLeft = "20px solid " + this.colors[pIndex % this.colors.length]; li.style.padding = "5px"; li.textContent = ctg; ul.append(li); pIndex++; } } draw() { this.drawGridLines(); this.drawBars(); this.drawLabel(); this.drawLegend(); } } var myBarchart = new BarChart({ canvas: myCanvas, seriesName: "Vinyl records", padding: 40, gridStep: 5, gridColor: "black", data: { "Classical Music": 16, "Alternative Rock": 12, Pop: 18, Jazz: 32 }, colors: ["#a55ca5", "#67b6c7", "#bccd7a", "#eb9743"], titleOptions: { align: "center", fill: "black", font: { weight: "bold", size: "18px", family: "Lato" } } }); myBarchart.draw(); Which will produce a final result looking like this: Try passing different options to the chart to see how it affects the final result. As an exercise, can you write to code make those grid lines multi-colored? CongratulationsWe have seen that drawing charts using the HTML5 canvas is actually not that hard. It only requires a bit of math and a bit of JavaScript knowledge. You now have everything you need for drawing your own bar charts. This post has been updated with contributions from Nitish Kumar. Nitish is a web developer with experience in creating eCommerce websites on various platforms. He spends his free time working on personal projects that make his everyday life easier or taking long evening walks with friends. How do you create a bar graph using HTML?There are 4 basic steps you should take to create a simple bar chart for your application or website: Create an HTML page. Reference all necessary files.. Create an HTML page. ... . Reference all necessary files. ... . Put together the data. ... . Write the code for the chart.. How do you plot a graph in HTML?That's all!. Typical Scatter Chart Syntax: var myChart = new Chart("myChart", { type: "scatter", data: {}, options: {} });. Typical Line Chart Syntax: var myChart = new Chart("myChart", { type: "line", data: {}, options: {} ... . Typical Bar Chart Syntax: var myChart = new Chart("myChart", { type: "bar", data: {}, options: {}. How do I make a bar chart in HTML CSS?#1 Bar Chart HTML - Using Only HTML And CSS. <h1>Bar Chart HTML</h1>. <div class="chart-wrap vertical">. <h2 class="title">Bar Chart HTML Example: Using Only HTML And CSS</h2>. <div class="grid">. <div class="bar" style="--bar-value:85%;" data-name="Your Blog" title="Your Blog 85%"></div>. Does HTML have graphs?HTML Canvas Can Draw Graphics
Canvas has great features for graphical data presentation with an imagery of graphs and charts.
|