旋转带有两个数据点的chart.js饼图以在水平轴上对齐两个扇区

时间:2019-05-14 08:26:50

标签: javascript rotation chart.js

在StackOverflow上有一些答案,其中提供了有关如何使用Chart.js的固定值和rotation选项旋转饼图的建议,但我还没有找到如何创建旋转公式的方法计算实际数据值并旋转图表,以使其扇区始终在水平轴上对齐。

一个例子:

https://i.imgur.com/RcpKlNw.png

(无法在此处嵌入图片;因此一直说它无法连接到Imgur)。

是否有Chart.js选项可以对齐扇形扇形中心轴,还是我必须自己计算旋转角度?

例如,使用数据值[5,10],我可以使用公式rotation: 120/180 * Math.PI实现所需的轮换,但是我不确定如何使公式适用于动态值。

1 个答案:

答案 0 :(得分:1)

好吧,看来我使用自定义公式正确了。不确定,也许可以用更少的精力来完成:

var t1 = 5; // this will come from the server
var t2 = 10; // this will come from the server
var total = t1 + t2; 

// Chart.js draws the first data point from vertical axis
// by default. But if set rotation to 0, it draws at 90 degrees from vertical axis
// (that is - on horizontal axis to the right side).
// Calculating the chart rotation, so that the first sector
// is always facing the left side and is middle-aligned
// on horizontal axis, 
// thus the second sector also will be aligned to the right side.
var percentageOfT1 = t1 / total;
var sectorSizeDeg = 360.0 * percentageOfT1; // circle is 360 degrees 
// thus we can calculate sector degrees easily using the percentage
var halfOffsetDeg = sectorSizeDeg / 2.0;

// rotate 180-halfsector 
// to compensate for horizontal align and reach the middle line of the sector
var finalOffsetDeg = 180.0 - halfOffsetDeg;

...
// in Chart options:
rotation: finalOffsetDeg / 180.0 * Math.PI