Chartjs-Rotate chart "pie" to need value or angle

0👍

This could help you:

var config = {
  type: 'pie',
  data: {
    datasets: [{
      data: [
        300,
        700
      ],
      backgroundColor: [
        window.chartColors.red,
        window.chartColors.blue,
      ],
      label: 'Dataset 1'
    }]
  },
  options: {
    responsive: true,
    rotation: 0,
    animation: {
      duration: 2000
    }
  }

};
var myPie;
window.onload = function() {
  create();
};

function create() {
  var ctx = document.getElementById('chart-area').getContext('2d');

  config.data.datasets[0].data = [$("#redValue").val(), $("#blueValue").val()]
  config.options.rotation = -Math.PI / 2;
  config.options.animation.duration = 2000;
  myPie = new Chart(ctx, config);
  // console.log(myPie);
}

function rotate() {
  var fromDegree = 0;
  var toDegree = 360 * (parseFloat($("#stopValue").val())) /
    (parseFloat($("#redValue").val()) + parseFloat($("#blueValue").val()));

  rotatePie(0, 360, 8,
    function() {
      rotatePie(0, 360, 15,
        function() {
          rotatePie(fromDegree, toDegree, 30,
            function() {})
        })
    });
}

function rotatePie(fromDegree, toDegree, delay, callback) {
  var rotation = -Math.PI / 2 - fromDegree * 2 * Math.PI / 360;
  var stopRotation = -Math.PI / 2 - toDegree * 2 * Math.PI / 360;

  var intervalId = setInterval(frame, delay);

  function frame() {
    if (rotation <= stopRotation) {
      console.log('2');
      clearInterval(intervalId);
      callback();
    } else {
      rotation = rotation - Math.PI * 0.03;
      myPie.config.options.rotation = rotation;
      myPie.config.options.animation.duration = 0;
      myPie.update();
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.chartjs.org/samples/latest/utils.js"></script>
<script src="https://www.chartjs.org/dist/2.7.3/Chart.bundle.js"></script>

<div id="canvas-holder" style="width:40%; margin: 20px">
  <canvas id="chart-area"></canvas>
</div>

Red Value: <input id="redValue" type="number" value="300" />
<br/> Blue Value: <input id="blueValue" type="number" value="700" />
<br/>
<button type="button" onclick="create()">Create</button>

<br/> <br/> Stop On: <input id="stopValue" type="number" value="350" />
<br/><br/>

<button type="button" onclick="rotate()">Rotate</button>

Leave a comment