var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
ctx.lineWidth = 2;
ctx.font = '12px verdana';
var PI2 = Math.PI * 2;
var myColor = ["white", "white", "white"];
var myData = [30, 60, 29];
var myLabels = ["A", "B", "C"];
var cx = 150;
var cy = 150;
var radius = 80;
pieChart(myData, myColor, myLabels);
function pieChart(data, colors, myLabels) {
var total = 0;
for (var i = 0; i < data.length; i++) {
total += data[i];
}
var sweeps = []
for (var i = 0; i < data.length; i++) {
sweeps.push(data[i]/total * PI2);
}
var accumAngle = 0;
for (var i = 0; i < sweeps.length; i++) {
drawWedge(accumAngle, accumAngle + sweeps[i], colors[i], data[i], myLabels[i]);
accumAngle += sweeps[i];
}
}
function drawWedge(startAngle, endAngle, fill, label, letter) {
// draw the wedge
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.arc(cx, cy, radius, startAngle, endAngle, false);
ctx.closePath();
ctx.fillStyle = fill;
ctx.strokeStyle = 'black';
ctx.fill();
ctx.stroke();
// draw the label in middle of sector
var midAngle = startAngle + (endAngle - startAngle)/2;
var labelRadius = radius * 0.5;
var x = cx + (labelRadius) * Math.cos(midAngle);
var y = cy + (labelRadius) * Math.sin(midAngle);
ctx.fillStyle = 'green';
ctx.fillText(label, x, y);
// draw the label in middle of arc on exterior
var midAngle = startAngle + (endAngle - startAngle)/2;
var labelRadius = radius * 1.25;
var x = cx + (labelRadius) * Math.cos(midAngle);
var y = cy + (labelRadius) * Math.sin(midAngle);
ctx.fillStyle = 'black';
ctx.fillText(label, x, y);
// draw the the label at start of sector
var midAngle = startAngle;
var labelRadius = radius * 1.25;
var x = cx + (labelRadius) * Math.cos(midAngle);
var y = cy + (labelRadius) * Math.sin(midAngle);
ctx.fillStyle = 'red';
ctx.fillText(label, x, y);
// draw the the label at end of sector
var midAngle = endAngle;
var labelRadius = radius * 1.5;
var x = cx + (labelRadius) * Math.cos(midAngle);
var y = cy + (labelRadius) * Math.sin(midAngle);
ctx.fillStyle = 'blue';
ctx.fillText(letter, x, y);
}
<section>
<div>
<table width="80%" cellpadding=1 cellspacing=1 border=0>
<tr>
<td width=50%>
<canvas id="canvas" align="center" width="400" height="300"> This text is displayed if your browser does not support HTML5 Canvas. </canvas>
</td>
</tr>
</table>
</div>
</section>
精美的作品!謝謝您的幫助。從概念上講,儘管我不明白「ctx.fillText(letter,x,y)」是如何知道從「myLabels」中獲取字母的。兩者之間的聯繫在哪裏建立起來的? – Snoops
我upvoted :)不知道你是否看到我的最後評論的編輯:我只是看通過代碼,並認識到,從概念上說,我不明白「ctx.fillText(letter,x,y)」知道如何從「myLabels」中取出信件。兩者之間的聯繫在哪裏建立起來的? – Snoops
謝謝。我想我明白了。所以''drawWedge(startAngle,endAngle,fill,label,letter)'自動將它的5個元素與'drawWedge(accumAngle,accumAngle + sweeps [i],colors [i],data [i],myLabels [i])等同起來「很明顯,我是新來的編程,所以我只是想確保我理解所有的東西。 – Snoops