Home » bar graph » Simple bar graph in canvas.

Simple bar graph in canvas.

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

 &lt;canvas id=&quot;myCanvas&quot; width=&quot;400&quot; height=&quot;200&quot; style=&quot;border:1px solid #000000;&quot;&gt;<br />
&lt;/canvas&gt;

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

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

Js Fiddle Link

Leave a Reply

Subscribe

Join 901 other subscribers