Search code examples
javascriptjqueryhtmlcssflot

how to calculate the angle between the mid of a clicked donut element and the negative y-axis


enter image description hereConsider the following codesample donut chart using jquery-flot , now as i have added the 'image' class on click of the donut, i want to dynamically add the degree in the 'image' class so that the clicked item will be facing down at the bottom ( like on the -ve side of the y-axis ).`

var data = [{
    label: "Pause",
    data: 150
}, {
    label: "No Pause",
    data: 100
}, {
    label: "yes Pause",
    data: 80
}, {
    label: "Sleeping",
    data: 250
}];

var options = {
    series: {
        pie: {
            show: true,
            innerRadius: 0.5,
            radius: 1,
            startAngle: 1,

        }
    },
    grid: {
        hoverable: true,
        clickable: true
    },
    legend: {
    show: false
    },
    stroke: {
    width: 4
    },
    tooltip: true,
    tooltipOpts: {
        cssClass: "flotTip",
        content: "%s: %p.0%",
        defaultTheme: false
    }
};
$("#pie-placeholder").bind("plotclick", function(event, pos, obj) {
   $("#pie-placeholder").addClass('image')

    });
var plot = $.plot($("#pie-placeholder"), data, options);

`

Note:- this is done using Jquery flot


Solution

  • Here you can find my solution to your problem if I got you right.

    $("#pie-placeholder").bind("plotclick", function(event, pos, obj) {
    if (obj) {
        var percentInRads = 0.02;
        var currSegmentInRads = percentInRads * obj.datapoint[0]
        var currSegmentOffset = currSegmentInRads / 2;
        var currSegmentStart = currSegmentOffset >= 0.5 ? -0.5 + currSegmentOffset : 0.5 - currSegmentOffset;
        var total = 0;
        var beforeTotal = 0;
    
        for (var idx = 0; idx < data.length; idx++) {
          var segment = data[idx];
    
          if (idx < obj.seriesIndex) {
            beforeTotal += segment.data;
          }
    
          total += segment.data;
        }
    
        var beforePart = (beforeTotal / total * 100) * percentInRads;
        var chartStartAngle = currSegmentStart - beforePart;
    
        options.series.pie.startAngle = chartStartAngle;
        $.plot($("#pie-placeholder"), data, options);
        console.log(obj.series);
    }
    
    });