Mohmd Ali Mohmd Ali - 1 year ago 83
Javascript Question

Drawing PieChart using js

I need help in drawing a Pie Chart using JavaScript. I'm using Ajax to get my data and to fetch them properly inside a pie chart in my dashboard. Please keep in mind I'm getting my data using Ajax .

Dan Dan
Answer Source

This is a simple example of what you could do. You can use methods relating to Paths in JavaScript and obviously, adapt the code to use values from your Ajax files to include an accurate, up to date representation of your pie chart.

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

function toRadians(deg) {
    return deg * Math.PI / 180 //Converts degrees into radians

function startTop(deg) {
    return toRadians(deg - 90); //Positions 0deg at the top of the circle instead of the left or east of the circle

var cx = 100; //Centre of the circle, x co-ord
var cy = 75; //Centre of the circle, y co-ord
var radius = 50; //Radius of the circle

ctx.beginPath(); //Begins drawing the path. See link in "Edit" section
ctx.moveTo(cx,cy); //Moves the beginning position to cx, cy (100, 75)
ctx.arc(cx, cy, radius, startTop(0), startTop(50)); //	ctx.arc(cx, cy, radius, startAngle, endAngle, counterclockwise (optional));
ctx.lineTo(cx,cy); //Draws lines from the ends of the arc to cx and cy
ctx.closePath(); //Finishes drawing the path
ctx.fill(); //Actually draws the shape (and fills)
//Can use ctx.stroke() if you just want the border

ctx.fillStyle = "#c82124"; //Changes the color
ctx.arc(cx,cy,radius, startTop(50),startTop(168));

ctx.fillStyle = "#3370d4";
ctx.arc(cx,cy,radius, startTop(168),startTop(360));
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

See path methods

  1. beginPath()
  2. closePath()
  3. arc()
  4. moveTo()
  5. lineTo
  6. fill()
  7. stroke()
  8. fillStyle()

Edit 2
Although I am not familiar with Ajax you could do something similar to this JSFiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download