Skip to content

Simple Area Grpah in Canvas.

To create Area graph in Canvas first draw canvas

 <canvas id="myCanvas" width="400" height="250" style="border:1px solid #000000;">
</canvas> 

then execute JavaScript code as below

var s1 = [2, 6, 3, 9,10,5,12,7];

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var l= s1.length;
var m = 200/Math.max.apply(Math, s1);

ctx.beginPath();
ctx.moveTo(0,250);
var a=400/l;
var hm=400/l;

for(i=1;i&amp;lt;l+1;i++)
{
 ctx.lineTo(a,250-s1[i-1]*m);
 a=a+hm;
}
ctx.strokeStyle = "rgba(0,255,0,1)";
ctx.stroke();

ctx.lineTo(a,250);
ctx.lineTo(0,250);
ctx.closePath();
var grd = ctx.createLinearGradient(0, 0, 0, 400);
grd.addColorStop(0, "rgba(0,255,0,0.2)");
grd.addColorStop(1, "rgba(0,255,0,0.8)");
ctx.fillStyle = grd;
ctx.fill();
a=400/l;
for(i=1;i&amp;lt;l+1;i++)
{
 ctx.beginPath();
 ctx.arc(a, 250-s1[i-1]*m, 3, 0, 2 * Math.PI, false);
 ctx.fillStyle = "rgba(0,255,0,1)";
 ctx.fill();
 ctx.lineWidth = 3;
 ctx.strokeStyle = "rgba(0,255,0,1)";
 ctx.stroke();
 ctx.font = "11px Arial";
 ctx.fillStyle = 'black';
 ctx.fillText('aa', a-5, 250-s1[i-1]*m-10);
 a=a+hm;
}

jsFiddle link

Leave a Reply

%d bloggers like this: