Graph.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import {Object2D} from "../Object2D.js";
  2. import {Vector2} from "../math/Vector2.js";
  3. import {Box2} from "../math/Box2.js";
  4. import {DOM} from "./DOM";
  5. /**
  6. * Graph object is used to draw simple graph data into the canvas.
  7. *
  8. * Graph data is composed of X, Y values.
  9. *
  10. * @class
  11. * @extends {Object2D}
  12. */
  13. function Graph()
  14. {
  15. Object2D.call(this);
  16. /**
  17. * Graph object containing the size of the object.
  18. */
  19. this.box = new Box2(new Vector2(-50, -35), new Vector2(50, 35));
  20. /**
  21. * Color of the box border line.
  22. */
  23. this.strokeStyle = "rgb(0, 153, 255)";
  24. /**
  25. * Line width.
  26. */
  27. this.lineWidth = 1;
  28. /**
  29. * Background color of the box.
  30. */
  31. this.fillStyle = "rgba(0, 153, 255, 0.3)";
  32. /**
  33. * Minimum value of the graph.
  34. */
  35. this.min = 0;
  36. /**
  37. * Maximum value of the graph.
  38. */
  39. this.max = 10;
  40. /**
  41. * Data to be presented in the graph.
  42. *
  43. * The array should store numeric values.
  44. */
  45. this.data = [];
  46. }
  47. Graph.prototype = Object.create(Object2D.prototype);
  48. Graph.prototype.constructor = Graph;
  49. Graph.prototype.isInside = function(point)
  50. {
  51. return this.box.containsPoint(point);
  52. };
  53. Graph.prototype.draw = function(context, viewport, canvas)
  54. {
  55. if(this.data.length === 0)
  56. {
  57. return;
  58. }
  59. var width = this.box.max.x - this.box.min.x;
  60. var height = this.box.max.y - this.box.min.y;
  61. context.lineWidth = this.lineWidth;
  62. context.strokeStyle = this.strokeStyle;
  63. context.beginPath();
  64. var step = width / (this.data.length - 1);
  65. var gamma = this.max - this.min;
  66. context.moveTo(this.box.min.x, this.box.max.y - ((this.data[0] - this.min) / gamma) * height);
  67. for(var i = 1, s = step; i < this.data.length; s += step, i++)
  68. {
  69. context.lineTo(this.box.min.x + s, this.box.max.y - ((this.data[i] - this.min) / gamma) * height);
  70. }
  71. context.stroke();
  72. if(this.fillStyle !== null)
  73. {
  74. context.fillStyle = this.fillStyle;
  75. context.lineTo(this.box.max.x, this.box.max.y);
  76. context.lineTo(this.box.min.x, this.box.max.y);
  77. context.fill();
  78. }
  79. };
  80. export {Graph};