我正在尝试使用Canvas绘制圆环饼图。这几乎已经完成但面临调整切片位置的一些问题。
电流:
预期:
enter code here
http://jsfiddle.net/RgLAU/1/ 我想1.)黄色/蓝色从顶部2绘制。)想在甜甜圈内写一些文字。 这是我现在的工作:
答案 0 :(得分:1)
arc()
方法从形状右侧的水平线开始,位于形状高度的中间y位置。
您需要为每个开始和结束角度值添加偏移量。
对于您的文字,我不确定它应该显示什么,但设置上下文的textAlign = "center"
和textBaseline = "middle"
可以轻松定位到任意位置。
您修改过的代码的粗略未清理转储:
var canvas = document.getElementById("chart");
var chart = canvas.getContext("2d");
function drawdountChart(canvas) {
// text options
chart.textAlign = "center";
chart.textBaseline = "middle";
chart.font = "25px sans-serif";
// where is our arc start angle
var offset = 1.5 * Math.PI;
this.x, this.y, this.radius, this.lineWidth, this.strockStyle, this.from, this.to = null;
this.set = function(x, y, radius, from, to, lineWidth, strockStyle) {
this.x = x;
this.y = y;
this.radius = radius;
this.from = from;
this.to = to;
this.lineWidth = lineWidth;
this.strockStyle = strockStyle;
}
this.draw = function(data) {
canvas.beginPath();
canvas.lineWidth = this.lineWidth;
canvas.strokeStyle = this.strockStyle;
canvas.arc(this.x, this.y, this.radius, this.from + offset, this.to + offset);
canvas.stroke();
var numberOfParts = data.numberOfParts;
var parts = data.parts.pt;
var colors = data.colors.cs;
var df = 0;
for (var i = 0; i < numberOfParts; i++) {
canvas.beginPath();
canvas.strokeStyle = colors[i];
canvas.arc(this.x, this.y, this.radius, df + offset, df + (Math.PI * 2) * (parts[i] / 100) + offset);
canvas.stroke();
df += (Math.PI * 2) * (parts[i] / 100);
}
chart.fillStyle = 'white'
chart.fillText('hello', this.x, this.y);
}
}
var data = {
numberOfParts: 4,
parts: {
"pt": [20, 30, 25, 25]
}, //percentage of each parts
colors: {
"cs": ["red", "green", "blue", "yellow"]
} //color of each part
};
var drawDount = new drawdountChart(chart);
drawDount.set(150, 150, 100, 0, Math.PI * 2, 30, "#fff");
drawDount.draw(data);
<canvas id="chart" width="500" height="500" style="background-color:black"> </canvas>