Graph.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import {Object2D} from "../Object2D.js";
  2. import {Vector2} from "../math/Vector2.js";
  3. import {Box2} from "../math/Box2.js";
  4. import {Helpers} from "../utils/Helpers.js";
  5. import {Circle} from "./Circle.js";
  6. /**
  7. * Graph object is used to draw simple graph data into the canvas.
  8. *
  9. * Graph data is composed of X, Y values.
  10. *
  11. * @class
  12. * @extends {Object2D}
  13. */
  14. function Graph()
  15. {
  16. Object2D.call(this);
  17. /**
  18. * Graph object containing the size of the object.
  19. */
  20. this.box = new Box2(new Vector2(-50, -35), new Vector2(50, 35));
  21. /**
  22. * Color of the box border line.
  23. */
  24. this.strokeStyle = "rgb(0, 153, 255)";
  25. /**
  26. * Line width.
  27. */
  28. this.lineWidth = 1;
  29. /**
  30. * Background color of the box.
  31. */
  32. this.fillStyle = "rgba(0, 153, 255, 0.3)";
  33. /**
  34. * Minimum value of the graph.
  35. */
  36. this.min = 0;
  37. /**
  38. * Maximum value of the graph.
  39. */
  40. this.max = 10;
  41. /**
  42. * Data to be presented in the graph.
  43. *
  44. * The array should store numeric values.
  45. */
  46. this.data = [];
  47. }
  48. Graph.prototype = Object.create(Object2D.prototype);
  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};