How to draw charts with JavaScript and HTML5 canvas

Time:2021-3-31

How to draw charts with JavaScript and HTML5 canvas

Original text:https://code.tutsplus.com/zh-…
Original: John negoita
Translation:Stypstive

In this tutorial, I’ll show you how to use JavaScript and canvas to display digital information on pie and doughnut charts.

There are actually easier ways to create a chart than from zero to one, such as using theThis chart Library

How to draw charts with JavaScript and HTML5 canvas

But if you want to know what’s behind the library, read on.

What is a pie chart?

A chart is a tool for displaying data graphically. The pie chart shows the data in circles of cut components. The size of each piece represents the proportional size represented by the data value.

What is a doughnut?

In short, a doughnut is a variant of a pie chart. The difference is the center of each tangential pie, so that only the rim is visible. In this way, the chart is a circle as it is called.

Start painting with canvas

Before we draw a pie chart, let’s look at its components. Let’s first look at how to draw with canvas components and JavaScript

  • A line

  • A radian (part of a circle)

  • A color filled graph

To draw it with HTML canvas, we need to create a few things first:

Create a project folder and name itpiechart-tutorial
staypiechart-tutorialCreate an HTML file in the folderindex.htmlThis file will be HTML code.
A JS filescritp.jsstaypiechart-tutorialThis file in the folder will be JavaScript code.

We will be able to simplify, and then add some code to itindex.htmlMedium:

<html>
<body>
    <canvas id="myCanvas"></canvas>
  <script type="text/javascript"></script>
</body>
</html>

We have an ID ofmyCanvasOf<canvas>Elements. Then we go through<script>The tag loads JS code.

stayscript.jsThe JS code first gets the index of a canvas, and then sets the width and height of the canvas. To draw on canvas, we only need a 2D context, which contains all the drawing methods.

var myCanvas = document.getElementById("myCanvas");
myCanvas.width = 300;
myCanvas.height = 300;
 
var ctx = myCanvas.getContext("2d");

Now that we have set the width and height of canvas, we also get the index of canvas. Next, we define some reusable functions that we need to use when drawing pie charts. We add the function to the script.js File.

function drawLine(ctx, startX, startY, endX, endY){
    ctx.beginPath();
    ctx.moveTo(startX,startY);
    ctx.lineTo(endX,endY);
    ctx.stroke();
}

functiondrawLineFive parameters are accepted

  1. ctx: index to the drawing context

  2. startX: the X coordinate of the starting point of the line segment

  3. startY: Y coordinate of the starting point of the line segment

  4. endX: the X coordinate of the end point of the line segment

  5. endY: Y coordinate of the end point of the line segment

We callbeginPath()Let’s start the line. It tells the drawing context that we are going to draw something on canvas. We usemoveTo()To set the starting point, calllineTo()To indicate the end point, and then callstoke()To make a real drawing.

Now let’s see how we draw a part of a circle, also called a radian.

function drawArc(ctx, centerX, centerY, radius, startAngle, endAngle){
    ctx.beginPath();
    ctx.arc(centerX, centerY, radius, startAngle, endAngle);
    ctx.stroke();
}

functiondrawArcAccept 6 parameters:

  1. ctx: index to the drawing context

  2. centerX: the X coordinate of the center of the circle

  3. centerY: Y coordinate of the center of the circle

  4. radius: radius of the circle

  5. startAngle: the starting angle of the sector of a partial circle

  6. endAngle: the end angle of the sector of a partial circle

Now that we know how to draw lines and arcs, let me see how to draw colored shapes. Since our goal is to draw a pie chart, we create a function to draw the pie chart.

function drawPieSlice(ctx,centerX, centerY, radius, startAngle, endAngle, color ){
    ctx.fillStyle = color;
    ctx.beginPath();
    ctx.moveTo(centerX,centerY);
    ctx.arc(centerX, centerY, radius, startAngle, endAngle);
    ctx.closePath();
    ctx.fill();
}

functiondrawPieSliceSeven parameters are accepted

  1. ctx: index to the drawing context

  2. centerX: the X coordinate of the center of the circle

  3. centerY: Y coordinate of the center of the circle

  4. radius: radius of the circle

  5. startAngle: the starting angle of the sector of a partial circle

  6. endAngle: the end angle of the sector of a partial circle

  7. color: the color of the fill

The following are examples of calling these three functions:

drawLine(_ctx,100,100,200,200);
drawArc(_ctx, 150,150,150, 0, Math.PI/3);
drawPieSlice(_ctx, 150,150,150, Math.PI/2, Math.PI/2 + Math.PI/4, '#ff0000');

It will produce the following results:

How to draw charts with JavaScript and HTML5 canvas

Now that we have all the necessary tools to draw a pie chart, let’s see how to use them together.

Draw a pie chart

Conceptually, any chart has two parts:

  • The data model that contains the data to be presented. This is structured by a particular type of chart.

  • Graphical display is to display the data in the data model through visual elements according to the rules of mathematical formula.

Pie chart data model
In the way of structured pie chart data, the most commonly used is to use a series of categories and corresponding values, the value of each category is associated with the pie chart.

For example, the data model display of pie chart is grouped by genre. It looks like this:

  • Classical music: 10

  • Alternative rock: 14

  • Popular: 2

  • Jazz: 12

We can do it here script.js Add a JS object to the file to store the data model, as follows:

var myVinyls = {
    "Classical music": 10,
    "Alternative rock": 14,
    "Pop": 2,
    "Jazz": 12
};

Graphic display of pie chart
The pie chart uses circles to display the information in the data model, and cuts the circle into parts. Each copy corresponds to the category in the data model, and the size of each copy is directly proportional to the value of the corresponding category.

My music collection has four categories. The number of copies of each category in the pie chart is proportional to the corresponding value of its category.

But how do we measure the number of copies? Simple – we look at it from every angle. All we need to know is the number of copies of 360 degrees or 2pi. So a semicircle is 180 DEG or PI, a quarter circle is 90 degrees or pi / 2, and so on.

In order to determine the angle of each category, we use the following formula:

Share angle = 2 * pi * category value / total value

According to this formula, the approximation of classical music is as follows. 526 * PI or 94 degrees

Let me start painting. This time we’ll use the JavaScript class and name itPieChartThe constructor takes options as a parameter. Options include the following:

  • Canvas: index to the pie chart we want to draw

  • Data: index of the object holding the data model

  • Colors: an array of colors for each item.

PieChartClass also contains adraw()Method, which is used to actually draw the chart.

var Piechart = function(options){
    this.options = options;
    this.canvas = options.canvas;
    this.ctx = this.canvas.getContext("2d");
    this.colors = options.colors;
 
    this.draw = function(){
        var total_value = 0;
        var color_index = 0;
        for (var categ in this.options.data){
            var val = this.options.data[categ];
            total_value += val;
        }
 
        var start_angle = 0;
        for (categ in this.options.data){
            val = this.options.data[categ];
            var slice_angle = 2 * Math.PI * val / total_value;
 
            drawPieSlice(
                this.ctx,
                this.canvas.width/2,
                this.canvas.height/2,
                Math.min(this.canvas.width/2,this.canvas.height/2),
                start_angle,
                start_angle+slice_angle,
                this.colors[color_index%this.colors.length]
            );
 
            start_angle += slice_angle;
            color_index++;
        }
 
    }
}

ClassoptionsParameters are stored. It’s preservedcanvasAt the same time, a painting context is created as a class member variable. Then it stores thecolorsArray.

The next part is the most fundamental, functiondraw(). It extracts data from the data model. First, it calculates the sum of all data values in the data model. Then apply the above mentioned function to calculate the angle for each of these categories. Finally, we calldrawPieSlice()Function, using the center of canvas as the center of the pie chart. As for radius, we use the smaller value of half the width of canvas and half the height of canvas, because we don’t want the pie to go beyond canvas.

Similarly, each time you draw a category, you should offset the start angle and end angle of each category, otherwise there will be overlap.

To use a class, we must first create an instance object and then call it on the created objectdraw()method.

var myPiechart = new Piechart(
    {
        canvas:myCanvas,
        data:myVinyls,
        colors:["#fde23e","#f16e23", "#57d9ff","#937e88"]
    }
);
myPiechart.draw();

The results look like this:

How to draw charts with JavaScript and HTML5 canvas

Drawing a circle

We’ve seen how to create a pie chart. Similarly, we can see that the difference between the doughnut chart and the pie chart is that there is a hole in the middle. How to draw a hole? We can draw a white circle on the pie chart.

Let’s revise itPieChartClass to do it.

var Piechart = function(options){
    this.options = options;
    this.canvas = options.canvas;
    this.ctx = this.canvas.getContext("2d");
    this.colors = options.colors;
 
    this.draw = function(){
        var total_value = 0;
        var color_index = 0;
        for (var categ in this.options.data){
            var val = this.options.data[categ];
            total_value += val;
        }
 
        var start_angle = 0;
        for (categ in this.options.data){
            val = this.options.data[categ];
            var slice_angle = 2 * Math.PI * val / total_value;
 
            drawPieSlice(
                this.ctx,
                this.canvas.width/2,
                this.canvas.height/2,
                Math.min(this.canvas.width/2,this.canvas.height/2),
                start_angle,
                start_angle+slice_angle,
                this.colors[color_index%this.colors.length]
            );
 
            start_angle += slice_angle;
            color_index++;
        }
 
        //drawing a white circle over the chart
        //to create the doughnut chart
        if (this.options.doughnutHoleSize){
            drawPieSlice(
                this.ctx,
                this.canvas.width/2,
                this.canvas.height/2,
                this.options.doughnutHoleSize * Math.min(this.canvas.width/2,this.canvas.height/2),
                0,
                2 * Math.PI,
                "#ff0000"
            );
        }
 
    }
}

The added code is in theoptionsParameter, through adoughnutHoleSizeMember variable. If this parameter is not passed in options, the code will draw as before. If it is passed, draw a white circle in the center of the pie chart.

The radius of a circle is determined by the sum of the radius of a pie graphdoughnutHoleSizeIt is determined by the product of the parameters. It should be a number between 0 and 1. 0 represents a pie chart. When the value is greater than 0, the larger the hole in the middle of the pie chart is. When the value is 1, the chart will not be visible.

To draw a circle half the size of a graph, we candoughnutHoleSizeSet to 0.5 and call as follows:

var myDougnutChart = new Piechart(
    {
        canvas:myCanvas,
        data:myVinyls,
        colors:["#fde23e","#f16e23", "#57d9ff","#937e88"],
        doughnutHoleSize:0.5
    }
);
myDougnutChart.draw();

Here are the results:

How to draw charts with JavaScript and HTML5 canvas

Add labels and chart Legends

Our pie chart and circle chart look great, but it’s going to get better by adding two things:

  • Value tag: displays the percentage of each item

  • Chart legend: displays the corresponding relationship between each category and color in the chart

In general, the value of each piece is expressed as a percentage, which is expressed by100 * each value / total valueTo calculate, the whole circle represents100%

For example, in our example data, classical music can be approximated by26%To express. It would be great if you could just display this value on the corresponding portion. To do this, we can use thefillText(text, x, y)Function. This function takes three arguments: text and textxyCoordinates.

How to calculate the position of textxandyWhat about the coordinates? We’re going to have to use some geometry, something called polar coordinates. Generally, polar coordinates define the position of a point by radius and angle. The two formulas we will use are:

x = R * cos(angle)

y = R * sin(angle)

We’re going to apply this formula to place the text at half the radius of the pie and half the angle of each pie. To do this, we need to modify our piechart class and add the following code in theif(this.options.doughnutHoleSize){...}Code block.

...
start_angle = 0;
for (categ in this.options.data){
    val = this.options.data[categ];
    slice_angle = 2 * Math.PI * val / total_value;
    var pieRadius = Math.min(this.canvas.width/2,this.canvas.height/2);
    var labelX = this.canvas.width/2 + (pieRadius / 2) * Math.cos(start_angle + slice_angle/2);
    var labelY = this.canvas.height/2 + (pieRadius / 2) * Math.sin(start_angle + slice_angle/2);
 
    if (this.options.doughnutHoleSize){
        var offset = (pieRadius * this.options.doughnutHoleSize ) / 2;
        labelX = this.canvas.width/2 + (offset + pieRadius / 2) * Math.cos(start_angle + slice_angle/2);
        labelY = this.canvas.height/2 + (offset + pieRadius / 2) * Math.sin(start_angle + slice_angle/2);               
    }
 
    var labelText = Math.round(100 * val / total_value);
    this.ctx.fillStyle = "white";
    this.ctx.font = "bold 20px Arial";
    this.ctx.fillText(labelText+"%", labelX,labelY);
    start_angle += slice_angle;
}
...

The above code traverses each part, calculates the percentage and location, and then calls.fillText()Method to plot it on a chart. We used itfillStyleProperty to set the text color to white,fontProperty to set the font, style, and size of the label text. It is also important to note that thedoughnutHoleSizeAfter setting, the label will be pushed to the edge so that the text can be in the center of the doughnut.

Here’s what a chart with value labels looks like:

How to draw charts with JavaScript and HTML5 canvas

The last thing to complete the chart is to add a legend to it. Our chart legend will show the categories of data in the data model and the corresponding colors. First, we need toindex.htmlMake some changes to the file and add one<div>Tags are used to store our legend elements.

<html>
<body>
    <canvas id="myCanvas"></canvas>
    <div id="myLegend"></div>
    <script type="text/javascript"></script>
</body>
</html>

And then in thescript.jsIn, we add the code to create the legend element. We add the code to thePieChartIn classdraw()The end of the function.

...
        if (this.options.legend){
            color_index = 0;
            var legendHTML = "";
            for (categ in this.options.data){
                legendHTML += "<div><span style='display:inline-block;width:20px;background-color:"+this.colors[color_index++]+";'>&nbsp;</span> "+categ+"</div>";
            }
            this.options.legend.innerHTML = legendHTML;
        }
...

Code passed inoptionsParameterslegendElements. If found, fill in the name of the colored block and data model category.

At the same time, we also need to change the code that calls plotting value chart to the following form:

var myLegend = document.getElementById("myLegend");
 
var myDougnutChart = new Piechart(
    {
        canvas:myCanvas,
        data:myVinyls,
        colors:["#fde23e","#f16e23", "#57d9ff","#937e88"],
        legend:myLegend
    }
);
myDougnutChart.draw();

This is the chart and legend of the results:

How to draw charts with JavaScript and HTML5 canvas

congratulations

We can see that it is not so difficult to draw charts with HTML5 canvas. It just needs a little bit of math and JavaScript. You now have all the information to draw your own pie chart and doughnut.

If you want a quick and easy solution, create pie charts and doughnuts, as well as other types of charts. You can download itInformation chart and HTML chart tag libraryOr WordPress plug-inCharts and Graphs WordPress Visual Designer

About envato art cloud platform

How to draw charts with JavaScript and HTML5 canvas

Envato cloud platformIt is a global leading market platform for data assets and creative talents. Millions of people around the world choose to buy documents, hire freelancers, or learn the skills they need to create websites, make videos, apply and draw through our marketing platforms, studios and courses. Our sub websites include the global largest H5, PS, illustration, code and photography tutorial resource library, as well as the envato cloud platform market, in which more than 9 million types of digital assets are sold through the following seven platforms-CodeCanyonIn addition, it is also found that there are three kinds of new products: Doce River, audioriver, audiovideo, and so on.