Skip to content

Simple bar graph in canvas.

Creating bar-graph in canvas is very easy.
In Body Section in html file

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

In Script Section in html file

var s1 = [2, 6, 3, 9];
var ticks = ['a', 'b', 'c', 'd'];
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var l= 4;
for(i=0;i<4;i++)
{
  ctx.fillStyle = "#ccccdf";
  ctx.fillRect(25+(i*100),200-(s1[i]*20),50,(s1[i]*20));
  ctx.font = "20px Arial";
    ctx.fillStyle = "#000000";
	ctx.fillText(ticks[i],45+(i*100),190-(s1[i]*20));
}

here s1 is data arry to plot bar in canvas
and ticks is label for bar.

Js Fiddle Link

Leave a Reply

%d bloggers like this: