stats.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. function BarGraph(context) {
  2. var graph = this;
  3. this.values = [];
  4. this.labels = [];
  5. this.setLabels = function(labels){
  6. this.labels = labels;
  7. }
  8. this.setValues = function(values){
  9. this.values = values;
  10. }
  11. this.draw = function () {
  12. var values = graph.values;
  13. var barW;
  14. var barH;
  15. var barB = 1; // Border
  16. var ratio;
  17. var maxH;
  18. var max;
  19. var i;
  20. // Canvas dimensions
  21. context.canvas.width = graph.width;
  22. context.canvas.height = graph.height;
  23. // Width of each bar
  24. barW = graph.width / values.length - graph.margin * 2;
  25. maxH = graph.height - 25;
  26. // Reference height
  27. var max = 0;
  28. for (i = 0; i < values.length; i ++) {
  29. if (values[i] > max) {
  30. max = values[i];
  31. }
  32. }
  33. // Loop bars
  34. for (i = 0; i < values.length; i ++) {
  35. // Compare with the max value
  36. barH = maxH * values[i] / max;
  37. graph.height -= 15;
  38. // Value
  39. context.fillStyle = "#003300";
  40. context.font = "bold 12px sans-serif";
  41. context.textAlign = "center";
  42. context.fillText(parseInt(values[i], 10), i * graph.width / values.length + (graph.width / values.length) / 2, graph.height - barH - 3);
  43. // Bar background (border)
  44. context.fillStyle = "#003300";
  45. context.fillRect(graph.margin + i * graph.width / values.length, graph.height - barH, barW, barH);
  46. // Bar fill
  47. context.fillStyle = "#ccffcc";
  48. context.fillRect(graph.margin + i * graph.width / values.length + barB, graph.height - barH + barB, barW - barB * 2, barH - barB * 2);
  49. // Label
  50. graph.height += 15;
  51. context.fillStyle = "#003300";
  52. context.font = "10px sans-serif";
  53. context.textAlign = "center";
  54. context.fillText(graph.labels[i], i * graph.width / values.length + (graph.width / values.length) / 2, graph.height - 5);
  55. }
  56. };
  57. this.width = 450;
  58. this.height = 150;
  59. this.margin = 1;
  60. }