javascript - 使用js绘制饼图

标签 javascript php html ajax

我需要使用 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>

编辑
查看路径方法

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

编辑2
虽然我不熟悉Ajax,但你可以做类似的事情JSFiddle

关于javascript - 使用js绘制饼图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38687602/

相关文章:

php - FOSRestBundle jsonp请求强制下载

php - isset() 为不存在的数组键返回 true 的奇怪行为

html - 从外部链接转到特定部分

javascript - 在 Canvas 上应用平滑滤镜

html - 如何将具有 table-cell 显示属性的 html 元素向右推送?

javascript - 这个 Javascript 语句是什么意思?

javascript - 如何生成5个不同的随机数?

php 脚本没有打开欢迎页面,也没有使用 wamp 写入数据库

javascript - Highchart 多轴 - 在多个图表上同步轴

javascript - 大视频上传处理超时