如何在charts.js 中旋转饼图?

2022-01-22 00:00:00 canvas jquery javascript css chart.js

看起来像 charts.js 中的饼图是通过在圆的上半部分取垂直半径,然后从那里顺时针移动来绘制的.这在大多数情况下都很好用,但是对于只有 2 个类别的饼图,如果可以旋转它以使切片居中,那就太好了,如下所示:

It looks like a pie in charts.js is drawn by taking a vertical radius on the top half of the circle, and then moving clockwise from there. This works great most of the time, but for a pie with only 2 categories, it would be nice if it could be rotated so that the slice is centered, like this:

旋转是通过取 360 的百分比并除以 2 来计算的.(.14*360)/2 = 25.2 度左,所以如果我可以申请的话

The rotation is calculated by taking the percentage of 360 and dividing by 2. (.14*360)/2 = 25.2 degrees left, so if I could just apply

transform: rotate(-25.2deg);

到那个圈子我就好了.

由于 charts.js 将它放在画布上(而不是 <svg>),我不知道如何对其应用任何转换.不确定是否相关,但这是我的图表代码:

Since charts.js puts this on a canvas (as opposed to <svg>) I don't know how to apply any transformations to this. Not sure if relevant, but here is my code for the chart:

HTML

<canvas id=canvas style='width:300px;height:300px;'></canvas>

JS

openRate = [
            {
                value: 488,
                color: "#FF9030",
                highlight: "rgba(255, 144, 48, 0.44)",
            },
            {
                value: 3475,
                color: "#008DB7",
                highlight: "rgba(0, 141, 183, 0.82)"
            }
        ];

var ctx=document.getElementById('canvas').getContext("2d");
var chart=new Chart(ctx).Pie(openRate);

还有一个小提琴:http://jsfiddle.net/msy6kf3a/

推荐答案

你可以使用

chartjs中的轮换选项

我正在使用版本:2.1.6"

I'm using "Version: 2.1.6"

var options = {
   rotation: (-0.5 * Math.PI) - (25/180 * Math.PI)
}

var Chart = new Chart(ctx,{
  type: 'pie',
  data: data,
  options: options
});

更新了 fiddle

相关文章