Skip to main content

Line/Bar Graphs using Canvas in HTML5

<canvas id="tutorial1" width="350" height="200" style="border: 1px solid black;">
<script>
var canvas = document.getElementById('tutorial1');
var ctx = canvas.getContext('2d');
ht = canvas.height; wt = canvas.width ;
var data = {};
data.gtype = 'line';
data.title = 'hey! title goes here';
data.data = [['Q1',10],['Q2',20],['Q3',30],['Q4',40],['Q5',25]];


ctx.drawCross = function (x,y){
    this.beginPath();
    this.moveTo(x + 5, y + 5);
    this.lineTo(x - 5, y - 5);
    this.closePath();
    this.stroke();

    this.beginPath();
    this.moveTo(x - 5, y + 5);
    this.lineTo(x + 5, y - 5);
    this.closePath();
    this.stroke();
}


ctx.fillStyle = "Red";

ctx.beginPath();
ctx.moveTo(40,10);
ctx.lineTo(40,ht-40);
ctx.lineTo(wt-10,ht-40);
ctx.stroke();
ctx.closePath();
/* draw title*/
len = ctx.measureText (data.title);
ctx.fillText(data.title, (wt -len.width) /2  , ht-5 );

x = 40;
y = 10;

var datArray = [];
for( i =0 ; i < data.data.length ; i++ ){
    datArray.push( data.data[i][1]);
}
   
MAX = Math.max.apply(null, datArray) ;
Ratio = ( ht - x - y - 10 ) / MAX ;
xadjust = ( ( wt - 50 ) / datArray.length ) - 5 ;
tasks = [];
tasks.popall=function(){
  if(this.length == 0) return this;
  while(this.length != 0) eval(this.pop());
  return this;
};

ctx.fillStyle = "Black";

for( i =0 ; i < data.data.length ; i++ ){
    d = data.data[i][1];
    
    hhh = Ratio*d ;
    y = ht-40-hhh;
    x = x + xadjust;

    if(data.gtype=='bar'){
        ctx.fillRect( x , y , 5 , hhh );
    }
    
    else if(data.gtype=='line'){
        if(i!=0){
            ctx.lineTo(x,y);
        }else{
            ctx.beginPath();
            ctx.moveTo(x,y);
        }
        tasks.push( 'ctx.drawCross('+eval(x)+','+eval(y)+')' ) ;
    }
    
    ctx.fillText( data.data[i][0] , x , ht - 28  );
    /*ctx.fillText( data.data[i][1] , 20 , y+5 );*/
}
    if(data.gtype=='line'){ ctx.stroke(); tasks.popall();  }
<⁄script>

Just by changing the data.gtype from 'line' to 'bar' on line 7, the graph type can be changed.
Final Product Line Graph:

Bar Graph:

I know that there are a lot of to-do's here. A small list would be:
  1. Titles for the x and y axes.
  2. Markers for the y-axis
  3. Clearing up the code and commenting it so as to make it easier to follow.
I hope to do it sometime this week.

Comments