HTML5 Canvas 饼图 [英] HTML5 Canvas pie chart
问题描述
我正在尝试创建一个简单的饼图,如下图所示:
I'm attempting to create a simple pie chart like shown in the graphic below:
图表将显示测验的结果,用户可以选择 a、b 或 c.它们有 10 个问题,用户每个问题只能选择一个选项.
The chart will show the results for a quiz where a user can choose either a, b or c. They're 10 questions and the user can only choose one option per question.
我想要做的是通过传入 a、b 或 c 的值来显示饼图,其中每个段的百分比均为 100%.
What I want to do is show the pie chart with each segment being a percentage of 100% by passing in the values for either a,b, or c.
到目前为止,我有以下几点:
I have the following so far:
var greenOne = "#95B524";
var greenTwo = "#AFCC4C";
var greenThree = "#C1DD54";
function CreatePieChart() {
var chart = document.getElementById('piechart');
var canvas = chart.getContext('2d');
canvas.clearRect(0, 0, chart.width, chart.height);
var total = 100;
var a = 3;
var b = 4;
var c = 3;
for (var i = 0; i < 3; i++) {
canvas.fillStyle = "#95B524";
canvas.beginPath();
canvas.strokeStyle = "#fff";
canvas.lineWidth = 3;
canvas.arc(100, 100, 100, 0, Math.PI * 2, true);
canvas.closePath();
canvas.stroke();
canvas.fill();
}
}
CreatePieChart();
<canvas id="piechart" width="200" height="200"></canvas>
颜色特定于段的大小,因此最大的使用绿色一个,最小的使用绿色三个.
The colors are specific to the size of the segment, so green one is used for the largest and green three for the smallest.
谢谢
推荐答案
即使在搜索谷歌并三重检查我的弧度值等之后,我仍然仍然遇到这个问题,所以我创建了一个 jsFiddle 供人们作为一个活生生的例子来玩,并将在下面发布代码.(更新:在 fiddle v2 中,还添加了笔画和标签.)
Even after searching Google and triple-checking my radians values, etc. I was still having trouble with this, so I have created a jsFiddle for people to play with as a live example and will post the code below as well. (Update: in the fiddle v2, stroke and labels are added also.)
var canvas = document.getElementById("can");
var ctx = canvas.getContext("2d");
var lastend = 0;
var data = [200, 60, 15]; // If you add more data values make sure you add more colors
var myTotal = 0; // Automatically calculated so don't touch
var myColor = ['red', 'green', 'blue']; // Colors of each slice
for (var e = 0; e < data.length; e++) {
myTotal += data[e];
}
for (var i = 0; i < data.length; i++) {
ctx.fillStyle = myColor[i];
ctx.beginPath();
ctx.moveTo(canvas.width / 2, canvas.height / 2);
// Arc Parameters: x, y, radius, startingAngle (radians), endingAngle (radians), antiClockwise (boolean)
ctx.arc(canvas.width / 2, canvas.height / 2, canvas.height / 2, lastend, lastend + (Math.PI * 2 * (data[i] / myTotal)), false);
ctx.lineTo(canvas.width / 2, canvas.height / 2);
ctx.fill();
lastend += Math.PI * 2 * (data[i] / myTotal);
}
<canvas id="can" width="200" height="200" />
这篇关于HTML5 Canvas 饼图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!