BarGraph.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import {Object2D} from "../../Object2D.js";
  2. import {Graph} from "./Graph.js";
  3. /**
  4. * Bar graph can be used to plot bar data into the canvas.
  5. *
  6. * @class
  7. * @extends {Object2D}
  8. */
  9. function BarGraph()
  10. {
  11. Graph.call(this);
  12. /**
  13. * Width of each bar in the graph.
  14. *
  15. * If set null is automatically calculated from the graph size and number of points.
  16. *
  17. * @type {number}
  18. */
  19. this.barWidth = null;
  20. }
  21. BarGraph.prototype = Object.create(Graph.prototype);
  22. BarGraph.prototype.constructor = BarGraph;
  23. BarGraph.prototype.type = "BarGraph";
  24. Object2D.register(BarGraph, "BarGraph");
  25. BarGraph.prototype.draw = function(context, viewport, canvas)
  26. {
  27. if(this.data.length === 0)
  28. {
  29. return;
  30. }
  31. var width = this.box.max.x - this.box.min.x;
  32. var height = this.box.max.y - this.box.min.y;
  33. var step = width / (this.data.length - 1);
  34. var gamma = this.max - this.min;
  35. context.lineWidth = this.lineWidth;
  36. context.beginPath();
  37. var barWidth = this.barWidth !== null ? this.barWidth : width / this.data.length;
  38. var barHalfWidth = barWidth / 2.0;
  39. for(var i = 0, s = 0; i < this.data.length; s += step, i++)
  40. {
  41. var y = this.box.max.y - ((this.data[i] - this.min) / gamma) * height;
  42. context.moveTo(this.box.min.x + s - barHalfWidth, y);
  43. context.rect(this.box.min.x + s - barHalfWidth, y, barWidth, this.box.max.y - y);
  44. }
  45. if(this.strokeStyle !== null)
  46. {
  47. context.strokeStyle = this.strokeStyle.get(context);
  48. context.stroke();
  49. }
  50. if(this.fillStyle !== null)
  51. {
  52. context.fillStyle = this.fillStyle.get(context);
  53. context.fill();
  54. }
  55. };
  56. BarGraph.prototype.serialize = function(recursive)
  57. {
  58. var data = Graph.prototype.serialize.call(this, recursive);
  59. return data;
  60. };
  61. BarGraph.prototype.parse = function(data, root)
  62. {
  63. Graph.prototype.parse.call(this, data, root);
  64. };
  65. export {BarGraph};