zfrisch..
5
我喜欢上一个答案,但是我觉得它缺乏代码清晰度,并且没有真正涵盖如何使用标签。
我将值移到数据对象数组中以便于声明。我将其他值(例如百分比)明确声明为数据对象的属性或单独的变量。我认为,这更易于阅读。
如果您对此感兴趣,那么重构也使将值绑定到输入框变得更加容易。
要了解我的意思并使用这些值,请查看此CodePen:http ://codepen.io/zfrisch/pen/pRbZeb
var data = [{
label: "one",
value: 100,
color: 'white'
}, {
label: "two",
value: 100,
color: 'skyBlue'
}, {
label: "three",
value: 100,
color: 'yellow'
}];
var total = 0;
for (obj of data) {
total += obj.value;
}
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var previousRadian;
var middle = {
x: canvas.width / 2,
y: canvas.height / 2,
radius: canvas.height / 2,
};
//background
ctx.beginPath();
ctx.arc(middle.x, middle.y, middle.radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.stroke();
ctx.fillStyle = "black";
ctx.fill();
//end of background
for (obj of data) {
previousRadian = previousRadian || 0;
obj.percentage = parseInt((obj.value / total) * 100)
ctx.beginPath();
ctx.fillStyle = obj.color;
obj.radian = (Math.PI * 2) * (obj.value / total);
ctx.moveTo(middle.x, middle.y);
//middle.radius - 2 is to add border between the background and the pie chart
ctx.arc(middle.x, middle.y, middle.radius - 2, previousRadian, previousRadian + obj.radian, false);
ctx.closePath();
ctx.fill();
ctx.save();
ctx.translate(middle.x, middle.y);
ctx.fillStyle = "black";
ctx.font = middle.radius / 10 + "px Arial";
ctx.rotate(previousRadian + obj.radian);
var labelText = "'" + obj.label + "' " + obj.percentage + "%";
ctx.fillText(labelText, ctx.measureText(labelText).width / 2, 0);
ctx.restore();
previousRadian += obj.radian;
}