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

Popular posts from this blog

Yo mama so geeky : generating jokes using Markov Chains

A few days back, I saw this article “ How to fake a sophisticated knowledge of Wine with Markov Chains ” on the programming subreddit. To my utter delight, the article referenced the code, along with a very detailed explanation, so I spent an hour getting it all to work. The hour taken was no fault of the original authors, it was taken because I wanted to get a good hang of XPath, which will be the topic of a later post. The program auto-generates wine reviews, by using Markov Chains to come up with a sequence of most probable trigrams. It was great fun spouting my expert-level sommelier reviews, especially considering that I can count on one hand the number of times I have actually tasted wine! The reviews were just the right amount of ambiguous with a hint of snobbishness (which, according to me, just made the whole thing perfectly more believable). While I was showing off my new-found expertise in wines, my partner in crime,  Rupsa , told me it could probably be used for ot...

The first half of 2017 in review

Hi people, Half the year is over and i think its good to list out things, so that i have an idea as to how i am doing with my studies ( and pretty much everything else ). It's been a wonderful and fulfilling half year, to be honest. I did a lot of things I always wanted to do.  I started experimenting with hydroponics - haven't really progressed much, but I am sure I will do something substantial in the other half of the year. Benefits are a lot over traditional way, and the joy of watching your plants grow are invaluable, at the least. I read a few books on history. I have always wanted to do this , but I always had an excuse or 2 to avoid it. I finally started, and it's brought me a sense of childlike wonder, something I sorely missed. I cleaned my home! That's 20 years of procrastination right there! It was insane but I got it done. Whew! And wow!  At the beginning of the year, i finished my re-study of the CS subjects. Post February, i opened th...

Wicktionary Bookmarklet

A bookmarklet is defined by Wictionary as "A small piece of JavaScript code stored as a URL within a bookmark". I have been using bookmarklets to make my life easier from a long time. Some that I use regularly are [Read Now] : This makes it really easy for me to read pages which are unreadable. [Google Translate] : Translates pages [Mobilise This] : Formats the page for mobile viewing by Google. [Acronym lookup] : This helps me find the meanings for abbreviations. The links in [] brackets are bookmarklets. Just drag them to your bookmark bar. I picked these up from these two pages. There is also a whole website dedicated to them bookmarklets. As a developer, what i like about bookmarklets is that they are coded in JavaScript and i can meddle with them till my heart's content, without worrying about breaking anything. However, i wanted a bookmarklet that would allow me to look up meaning of words. Wiktionary was my open dictionary of choice. They d...