Drawing arc graph on Canvas

Adding Data to graph

The arc graph shows 0 value at left edge ( 0 degree ) and it shows maximum value at right edge ( 180 degree ). This is like our speed dial of vehicle.
We will pass two data to this graph , one is maximum value of the data which will match with 180 degree or right corner of the graph the second one is present value based on which our pointer will take position.
var max_data=600;
var pointer_data=500;
Using above two data we can find out the angle of the pointer.
From the height and width of the canvas we can set the values for other variables.
var my_canvas=$('#my_canvas').get(0)
var gctx = my_canvas.getContext("2d");
var x=my_canvas.width/2;  // x coordinate of center of the arc 
var y=my_canvas.height-60; // y coordinate of center of the arc, here some margin is left from bottom.  
var r=200; // Radius of the arc
var arc_width=50;  // Width of the arc with colour band
arc_angle=10; // angle of the arc at opposite end of the pointer. 
We will enter data at right end of the arc graph
gctx.font = '15px serif';
gctx.fillText(max_data, x+r+arc_width,y); // Write max_data at right side

Draw the arc

We will draw the arc and use strokeStyle to add colour gradient to it.
Colour gradient starts from left edge ( x-r ) to write edge ( x+r ). Here x is the centre point of the graph and r is the radius of the graph.
gctx.strokeStyle= my_gradient;
We will add shadow to this graph
gctx.shadowColor = 'black';
gctx.shadowBlur = 5;

Drawing of pinter

You can learn more on drawing of pointer from our analog clock drawing tutorial. Here is the code. We also added one small circle at center.
Note that we already calculated the starting angle ( ang_pointer ) by using the input data.
gctx.strokeStyle= '#46d2f5'; // border color of the second needle 
var startAngle=(1/180) * (ang_pointer); // In degree 
var a_start_ang=(1/180) * ((ang_pointer  -arc_angle));
var a_end_ang=(1/180) *((ang_pointer + arc_angle));

var y1=y- r*Math.sin(startAngle*Math.PI);
var x1=x- r*Math.cos(startAngle*Math.PI);

/// writing text at edge of the pointer ///
var y2=y- 1.3*r*Math.sin(startAngle*Math.PI);
var x2=x- 1.3*r*Math.cos(startAngle*Math.PI);
gctx.fillText(pointer_data, x2,y2);

gctx.moveTo(x1,y1); // Coordinate of tip of the needle
gctx.lineTo(x1,y1); // Full second needle path
gctx.fillStyle = '#46d2f5'; // fill colour of the second needle
gctx.stroke(); // draw the second needle 

/// small Circle at center of the clock 
gctx.strokeStyle= '#000000';
gctx.fillStyle = '#ff00ff';
Full Code is here

Subscribe to our mailing list

* indicates required
Subscribe to plus2net
Visitors Rating
Your Rating


Post Comment This is for short comments only. Use the forum for more discussions.

Subscribe to our mailing list

* indicates required
Subscribe to plus2net
HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us
©2000-2017 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer