代码之家  ›  专栏  ›  技术社区  ›  JustAMartin

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

  •  0
  • JustAMartin  · 技术社区  · 5 年前

    关于StackOverflow有一些答案,其中包括如何使用固定值和 rotation Chart.js的选项,但我还没有找到如何创建一个旋转公式来解释实际数据值并旋转图表,使其扇区始终在水平轴上对齐。

    例如:

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

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

    例如,使用数据值 [5,10] 我可以用公式实现所需的旋转 rotation: 120/180 * Math.PI

    0 回复  |  直到 5 年前
        1
  •  1
  •   JustAMartin    5 年前

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

    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