Draw Bar Graph using HTML5 Canvas

go to link What is bar graph?

A bar graph is a chart that uses either horizontal or vertical bars to show comparisons among categories. One axis of the chart shows the specific categories being compared, and the other axis represents a discrete value.

link Now the technicals –  how to draw the bar graph in Canvas?

In the body section just include the canvas tag with height and width

<canvas id="myCanvas" width="600" height="300" style="border:1px solid black;"> </canvas>

On discount research paper writing services window.onload function we have initiated the value & labels.

 
window.onload = function(){ 
    var data = [{
        label: "Sci-fi",
        value: 2 
    }, {
        label: "Action",
        value: 8 
    }, {
        label: "Romance",
        value: 6 
    }, {
        label: "Drama",
        value: 2 
    }, {
        label: "Comedy", 
        value: 4
}];
new BarChart({ canvasId: "myCanvas", data: data, color: "blue", 
               barWidth: 50, minValue: 0, maxValue: 10, gridLineIncrement: 2
    });
};

A new object of how to write graduate personal statement BarChart() constructor is constructed with other details like, color,width of the bar etc.

The http://www.suannmotorandpump.com.au/homework-help-app-android/ BarChart() constructor is like,

 
function BarChart(config){ 
     http://fecom.es/ghost-writer-online-subtitrat/ // user defined properties 
    this.canvas = document.getElementById(config.canvasId); 
    this.data = config.data; this.color = config.color; 
    this.barWidth = config.barWidth; 
    this.gridLineIncrement = config.gridLineIncrement;

    //  pay for essays online uk adjust max value to highest possible value divisible by the grid line increment value and less than the    
    //  http://04.ma/?p=business-plan-writers-singapore requested max value

    this.maxValue = config.maxValue - Math.floor(config.maxValue %
    this.gridLineIncrement); 
    this.minValue = config.minValue;

 http://www.3solarbids.com/government-homework-helper/     //constants
    this.font = "12pt Calibri"; 
    this.axisColor = "#555"; 
    this.gridColor = "#aaa"; 
    this.padding = 10;

 Genetically Modified Food Research Paper     // relationship
    this.context = this.canvas.getContext("2d"); 
    this.range = this.maxValue - this.minValue; 
    this.numGridLines = this.numGridLines = Math.round(this.range/ this.gridLineIncrement); 
    this.longestValueWidth = this.getLongestValueWidth(); 
    this.x = this.padding + this.longestValueWidth; 
    this.y = this.padding * 2; 
    this.width = this.canvas.width - (this.longestValueWidth + this.padding * 2); 
    this.height = this.canvas.height - (this.getLabelAreaHeight() + this.padding * 4);

 click     // draw bar chart 

    this.drawGridlines(); 
    this.drawYAxis(); 
    this.drawXAxis(); 
    this.drawBars(); 
    this.drawYVAlues(); 
    this.drawXLabels();

}

This function is used to draw the bar graph.
go here LabelAreaHeight() is used to set the height of the area for labels beneath the x axis,

 
     BarChart.prototype.getLabelAreaHeight = function(){ 
 http://masheroa.com/need-help-with-logic-homework/      /*
      * gets the label height by finding the max label width 
      * and using trig to figure out the projected height since 
      * the text will be rotated by 45 degrees
      */
     this.context.font = this.font;
     var maxLabelWidth = 0;
     for (var n = 0; n < this.data.length; n++) { 
         var label = this.data[n].label; 
         maxLabelWidth = Math.max(maxLabelWidth, this.context.measureText(label).width); 
     }
 see      /* 
      * return y component of the labelWidth which 
      * is at a 45 degree angle: 
      * a^2 + b^2 = c^2
      * a= b 
      * c = labelWidth 
      * a = height component of right triangle 
      * solve for a 
      */

      return Math.round(maxLabelWidth / Math.sqrt(2));
};

Define the http://mingazetdinov.16mb.com/?p=help-me-to-beginning-my-essay-on-global-warming getLongestValueWidth() method which returns the longest value text width,

 
BarChart.prototype.getLongestValueWidth = function(){ 
    this.context.font = this.font; 
    var longestValueWidth = 0; 
    for (var n = 0; n <= this.numGridLines; n++) {
        var value = this.maxValue - (n * this.gridLineIncrement);
        longestValueWidth = Math.max(longestValueWidth, this. context.measureText(value).width);
    } 
    return longestValueWidth;
};

Define the drawXLabels() method which draws the x axis labels,

 
BarChart.prototype.drawXLabels = function(){ 

    var context = this.context; 
    context.save(); 
    var data = this.data;
    var barSpacing = this.width / data.length; 
    for (var n = 0; n < data.length; n++) {
        var label = data[n].label; 
        context.save(); 
        context.translate(this.x + ((n + 1 / 2) * barSpacing),this.y + this.height + 10); 
        context.rotate(-1 * Math.PI / 4); // rotate 45 degrees 
        context.font = this.font; 
        context.fillStyle = "black"; 
        context.textAlign = "right"; 
        context.textBaseline = "middle"; 
        context.fillText(label, 0, 0); 
        context.restore();
   } 
   context.restore();
};

Define the drawYValues() method which draws the y axis values

 
BarChart.prototype.drawYVAlues = function(){ 

    var context = this.context; 
    context.save(); 
    context.font = this.font; 
    context.fillStyle = "black"; 
    context.textAlign = "right"; 
    context.textBaseline = "middle";
    for (var n = 0; n <= this.numGridLines; n++) { 
        var value = this.maxValue - (n * this.gridLineIncrement); 
        var thisY = (n * this.height / this.numGridLines) +this.y; 
        context.fillText(value, this.x - 5, thisY);
    } 
    context.restore();
};

Define the drawBars() method which loops through all of the data elements and draws a bar for each one,

 
BarChart.prototype.drawBars = function(){ 

     var context = this.context; 
     context.save(); 
     var data = this.data;
     var barSpacing = this.width / data.length; 
     var unitHeight = this.height / this.range;
     for (var n = 0; n < data.length; n++) {  
         var bar = data[n]; var barHeight = (data[n].value - this.minValue) * unitHeight; 
         // if bar height is less than zero, this means that its value is less than the min value. 
         // Since we don't want to draw 
         // bars below the x-axis, only draw bars whose height is greater than zero 
         if (barHeight > 0) {
             context.save();
             context.translate(Math.round(this.x + ((n + 1 / 2) * barSpacing)), Math.round(this.y + this.height));
             /* 
              * for convenience, we can draw the bars upside down 
              * starting at the x-axis and then flip 
              * them back into the correct orientation using 
              * scale(1, -1). This is a great example of how 
              * transformations can help reduce computations 
              */
             context.scale(1, -1);
             context.beginPath(); 
             context.rect(-this.barWidth / 2, 0, this.barWidth,barHeight);
             context.fillStyle = this.color; 
             context.fill(); 
             context.restore();
        }
     }
     context.restore();
};

Define the drawGridlines() method which draws horizontal gridlines on the bar chart,

 
BarChart.prototype.drawGridlines = function(){ 

    var context = this.context; 
    context.save(); 
    context.strokeStyle = this.gridColor; 
    context.lineWidth = 2;
    for (var n = 0; n < this.numGridLines; n++) {
        var y = (n * this.height / this.numGridLines) + this.y; 
        context.beginPath(); 
        context.moveTo(this.x, y); 
        context.lineTo(this.x + this.width, y); 
        context.stroke();
    } 
    context.restore();
};

Define the drawXAxis() method which draws the x axis,

 
BarChart.prototype.drawXAxis = function(){ 
    var context = this.context; 
    context.save(); 
    context.beginPath(); 
    context.moveTo(this.x, this.y + this.height); 
    context.lineTo(this.x + this.width, this.y + this.height); 
    context.strokeStyle = this.axisColor;
    context.lineWidth = 2; context.stroke(); 
    context.restore();
};

Define the drawYAxis() method which draws the y axis,

 
BarChart.prototype.drawYAxis = function(){ 

    var context = this.context; 
    context.save(); 
    context.beginPath(); 
    context.moveTo(this.x, this.y); 
    context.lineTo(this.x, this.height + this.y); 
    context.strokeStyle = this.axisColor; 
    context.lineWidth = 2;
    context.stroke(); 
    context.restore();
};

When the page loads, build the data and instantiate a new BarChart object with the window.onload discussed earlier.

A bar chart will need a bit more configuration to make it truly generic.

For our implementation of the BarChart class, we’ll need to pass in the canvas id, an array of data elements, the bar colors, the bar widths, the grid line increment which is the number of units between grid lines, the max value and the min value. The BarChart constructor uses six methods to render the bar chart—

drawGridlines(), drawYAxis(), drawXAxis(), drawBars(), drawYValues(), and drawXLabels()

The key to the BarChart class is the drawBars() method that iterates over all of the data elements, and then draws a rectangle for each one. The easiest way to draw each bar is to first invert the context vertically (so that positive values of y go up and not down), position the cursor on the x axis, and then draw a rectangle downwards whose height is equal to the value of the data element. As the context is inverted vertically, the bar will actually rise upwards.

The output will look like,

html5 canvas bar graph

Point to be noted, we have inserted dummy values for each labels. Those can be fetched from the application also instead of dummy value through Ajax, which we will cover in later post.

If you find this article helpful, you can connect us in Google+ and Twitter.

Enter your email address:

Delivered by FeedBurner

Leave a Reply

Your email address will not be published. Required fields are marked *