我需要使用 JavaScript 绘制饼图的帮助。我使用 Ajax 来获取数据并在仪表板的饼图中正确获取它们。请记住我正在使用 Ajax 获取数据。
最佳答案
这是您可以执行的操作的一个简单示例。您可以在 JavaScript
中使用与 Paths
相关的方法,显然,可以调整代码以使用 Ajax
文件中的值来包含准确的、最多饼图的日期表示。
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.beginPath();
ctx.fillStyle = "#c82124"; //Changes the color
ctx.moveTo(cx,cy);
ctx.arc(cx,cy,radius, startTop(50),startTop(168));
ctx.lineTo(cx,cy);
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.fillStyle = "#3370d4";
ctx.moveTo(cx,cy);
ctx.arc(cx,cy,radius, startTop(168),startTop(360));
ctx.lineTo(cx,cy);
ctx.closePath();
ctx.fill();
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
编辑
查看路径方法
编辑2
虽然我不熟悉Ajax
,但你可以做类似的事情JSFiddle
关于javascript - 使用js绘制饼图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38687602/