pie.html 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <!doctype html>
  2. <html>
  3. <head>
  4. <title>Pie Chart</title>
  5. <script src="../../Chart.min.js"></script>
  6. <script src="../utils.js"></script>
  7. </head>
  8. <body>
  9. <div id="canvas-holder" style="width:40%">
  10. <canvas id="chart-area"></canvas>
  11. </div>
  12. <button id="randomizeData">Randomize Data</button>
  13. <button id="addDataset">Add Dataset</button>
  14. <button id="removeDataset">Remove Dataset</button>
  15. <script>
  16. var randomScalingFactor = function() {
  17. return Math.round(Math.random() * 100);
  18. };
  19. var config = {
  20. type: 'pie',
  21. data: {
  22. datasets: [{
  23. data: [
  24. randomScalingFactor(),
  25. randomScalingFactor(),
  26. randomScalingFactor(),
  27. randomScalingFactor(),
  28. randomScalingFactor(),
  29. ],
  30. backgroundColor: [
  31. window.chartColors.red,
  32. window.chartColors.orange,
  33. window.chartColors.yellow,
  34. window.chartColors.green,
  35. window.chartColors.blue,
  36. ],
  37. label: 'Dataset 1'
  38. }],
  39. labels: [
  40. 'Red',
  41. 'Orange',
  42. 'Yellow',
  43. 'Green',
  44. 'Blue'
  45. ]
  46. },
  47. options: {
  48. responsive: true
  49. }
  50. };
  51. window.onload = function() {
  52. var ctx = document.getElementById('chart-area').getContext('2d');
  53. window.myPie = new Chart(ctx, config);
  54. };
  55. document.getElementById('randomizeData').addEventListener('click', function() {
  56. config.data.datasets.forEach(function(dataset) {
  57. dataset.data = dataset.data.map(function() {
  58. return randomScalingFactor();
  59. });
  60. });
  61. window.myPie.update();
  62. });
  63. var colorNames = Object.keys(window.chartColors);
  64. document.getElementById('addDataset').addEventListener('click', function() {
  65. var newDataset = {
  66. backgroundColor: [],
  67. data: [],
  68. label: 'New dataset ' + config.data.datasets.length,
  69. };
  70. for (var index = 0; index < config.data.labels.length; ++index) {
  71. newDataset.data.push(randomScalingFactor());
  72. var colorName = colorNames[index % colorNames.length];
  73. var newColor = window.chartColors[colorName];
  74. newDataset.backgroundColor.push(newColor);
  75. }
  76. config.data.datasets.push(newDataset);
  77. window.myPie.update();
  78. });
  79. document.getElementById('removeDataset').addEventListener('click', function() {
  80. config.data.datasets.splice(0, 1);
  81. window.myPie.update();
  82. });
  83. </script>
  84. </body>
  85. </html>