我的问题是我的甜甜圈图没有按我想要的那样工作。我想创建一个像这样的甜甜圈图:
但我的甜甜圈图现在看起来像这样:
如您所见,笔画不会在正确的方向上重叠。我想这可能是因为我开始从右到左画笔画。相反,它应该从左到右绘制它们,因此左侧的“圆形末端”是可见的,而不是右侧的圆形末端。
这是我到目前为止所尝试的:
//function to draw the donut chart, ctx = context, cx - cy = position, radius and arcwith
dmbChart(ctx, cx, cy, radius, arcwidth) {
var tot = 0;
var accum = 0;
var PI = Math.PI;
var PI2 = PI * 2;
var offset = -PI/2;
for(var i = 0; i < this.canvasValues.length; i++) {
tot += this.canvasValues[i];
}
//Donut Sectors Color: Draw each stroke based on the value (canvasValues) and Color (canvasColors)
for(var i = 0; i < this.canvasValues.length; i++) {
ctx.lineWidth = arcwidth;
ctx.beginPath();
ctx.lineCap = "round";
ctx.arc(cx, cy, radius, offset + PI2 * (accum/tot), offset + PI2 * ((accum + this.canvasValues[i]) / tot));
ctx.strokeStyle = this.canvasColors[i];
ctx.stroke();
accum += this.canvasValues[i];
}
}
正如你所看到的,我得到的值是每个笔画的长度和颜色的百分比。从顶部开始,我从顶部 -> 右侧 -> 底部 -> 左侧绘制每个,这就是结果。但是我怎样才能修改它以获得最上面的结果呢?
编辑: 在@Helder Sepulveda 的帮助下,我现在这样创建了它。我更改了很多计算,修复了更改带来的一些错误。现在唯一的问题是它没有开始在顶部绘制。如您所见,绿色笔划应从顶部开始:
function dmbChart(ctx, cx, cy, radius, arcwidth) {
var canvasValues = [30, 5, 15, 10, 10, 10, 10, 10];
var canvasColors = ["#10dc60", "#DDDDDD", "#0cd1e8", "#ffce00", "#7044ff", "#f04141", "#ffea00", "#ee82ee"];
ctx.lineWidth = arcwidth;
ctx.lineCap = "round";
var accum = canvasValues.reduce((a,b) => a + b, 0);
for (var i = canvasValues.length-1; i >= 0; i--) {
var radians = canvasValues[i] / 100 * 360 * Math.PI / 180
ctx.beginPath();
ctx.arc(cx, cy, radius, accum, accum - radians, true);
ctx.strokeStyle = canvasColors[i];
ctx.stroke();
accum -= radians;
}
ctx.beginPath();
ctx.arc(cx, cy, radius, accum, accum - (0.1 / 100 * 360 * Math.PI / 180), true);
ctx.strokeStyle = canvasColors[canvasColors.length - 1];
ctx.stroke();
}
白猪掌柜的
相关分类