Home » bar graph » Simple Area Grpah in Canvas.

Simple Area Grpah in Canvas.

To create Area graph in Canvas first draw canvas

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

then execute JavaScript code as below

<br />
var s1 = [2, 6, 3, 9,10,5,12,7];</p>
<p>var c = document.getElementById(&quot;myCanvas&quot;);<br />
var ctx = c.getContext(&quot;2d&quot;);<br />
var l= s1.length;<br />
var m = 200/Math.max.apply(Math, s1);</p>
<p>ctx.beginPath();<br />
ctx.moveTo(0,250);<br />
var a=400/l;<br />
var hm=400/l;</p>
<p>for(i=1;i&amp;amp;lt;l+1;i++)<br />
{<br />
 ctx.lineTo(a,250-s1[i-1]*m);<br />
 a=a+hm;<br />
}<br />
ctx.strokeStyle = &quot;rgba(0,255,0,1)&quot;;<br />
ctx.stroke();</p>
<p>ctx.lineTo(a,250);<br />
ctx.lineTo(0,250);<br />
ctx.closePath();<br />
var grd = ctx.createLinearGradient(0, 0, 0, 400);<br />
grd.addColorStop(0, &quot;rgba(0,255,0,0.2)&quot;);<br />
grd.addColorStop(1, &quot;rgba(0,255,0,0.8)&quot;);<br />
ctx.fillStyle = grd;<br />
ctx.fill();<br />
a=400/l;<br />
for(i=1;i&amp;amp;lt;l+1;i++)<br />
{<br />
 ctx.beginPath();<br />
 ctx.arc(a, 250-s1[i-1]*m, 3, 0, 2 * Math.PI, false);<br />
 ctx.fillStyle = &quot;rgba(0,255,0,1)&quot;;<br />
 ctx.fill();<br />
 ctx.lineWidth = 3;<br />
 ctx.strokeStyle = &quot;rgba(0,255,0,1)&quot;;<br />
 ctx.stroke();<br />
 ctx.font = &quot;11px Arial&quot;;<br />
 ctx.fillStyle = 'black';<br />
 ctx.fillText('aa', a-5, 250-s1[i-1]*m-10);<br />
 a=a+hm;<br />
}<br />

jsFiddle link

Leave a Reply

Subscribe

Join 901 other subscribers